How to Create a New Index for a Pandas Dataframe Object in Python


In this article, we show how to create a new index for a pandas dataframe object in Python.

So if a dataframe object has a certain index, you can replace this index with a completely new index.

Or you can take an existing column in the dataframe and make that column the new index for the dataframe.

This can be done with the built-in set_index() function in the pandas module.

With the set_index() function, we can make any column the new index for the dataframe.

So we show how to do this in the following code shown below.

So let's now go over the code.

So we first have to import the pandas module. We do this with the line, import pandas as pd.

as pd means that we can reference the pandas module with pd instead of writing out the full pandas each time.

We import rand from numpy.random, so that we can populate the DataFrame with random values. In other words, we won't need to manually create the values in the table. The randn function will populate it with random values.

We create a variable, dataframe1, which we set equal to, pd.DataFrame(randn(4,3),['A','B','C','D',],['X','Y','Z'])

This creates a DataFrame object with 4 rows and 3 columns.

The rows are 'A', 'B', 'C', and 'D'.

The columns are 'W', 'X', and 'Y'.

After we output the dataframe1 object, we get the DataFrame object with all the rows and columns, which you can see above.

We then create a new column called 'teams' and set it equal to 4 items: 'Knicks, 'Spurs', 'Cavs', 'Nets'

We then use the set_index() function to make this column the new index for the dataframe.

In this set_index() function, we specify the column we want to make the new index and then we must specify the statement, inplace=True. inplace=True makes this changed index permanent.

We then show the dataframe1 object and you can see that the column, 'teams', is now the new index of the dataframe object.

So this is how to create a new index for a pandas dataframe object in Python.

Related Resources

How to Randomly Select From or Shuffle a List in Python

HTML Comment Box is loading comments...