Make index as a column in Pandas | #21 of 53: The Complete Pandas Course

Опубликовано: 12 Май 2022
на канале: Selva Prabhakaran (ML+)
649
5

Course materials Github: https://github.com/machinelearningplu...

Join Pandas course on ML+: https://edu.machinelearningplus.com/c...
--------------------
Here is couple of very commonly used data manipulation activity.

That is to convert a column of a data frame to an index and an index to a column, we're going to use the same Hungary chicken box dataset. So what I want to do is, I have this date over here, I want to convert this date to the index, I want to put this date as the index, how you can do it is use the set index method set in place equal to true so yeah, so that you don't have to reassign it.

Let's run this and see the result. Now your column has been transferred as an index, the data has been transferred to an index, right, there is no column called date present here. Now, that's done. Now let's assume we receive the data frame like this. Alright, we receive a data frame like this. And from this data frame, you want to transfer this index to a column you want to consider this index as a column or change this index to a column.

How do you do that a couple of methods, you can create a new column by the name date itself, just like how you create a new column, just create a new column and assign to it the value of the index of that data frame. Let's see the output. The problem here is the new column that you created is getting assigned at the last, we don't want that we will ideally want it to come in the very first position.

So what we will do instead is use df dot insert method, specify the position specify the name of the column that you want to create, and specify the value that you want to assign to this particular column name, right. So I'm going to rerun this. Now data is present as an index here, run insert over here, see the data frame, we have a new column called date here. So this is one very useful way of doing it.

This in the insert method helps you to assign a column at a desired position by default goes to the right that you can avoid and make it come at the position that you want. Now, that is one method. The other method is use df dot reset index. By doing that your index simply gets converted to a column in a data frame. Very useful, very often used.