Home » Pandas Set Index

Set Index

Pandas set index() is used to set a List, Series or DataFrame as index of a Data Frame. We can set the index column while making a data frame. But sometimes a data frame is made from two or more data frames and then index can be changed using this method.

Syntax:

Parameters:

  • keys: Refers to label or array-like or list of labels/arrays

It can be either a single column key, a single array of the same length as the calling DataFrame, or also a list that contains an arbitrary combination of column keys and arrays.

  • drop: Returns the boolean value, default value is True. Used to delete the columns that are to be used as the new index.
  • append: Returns the boolean value, default value is False.

It checks whether append the columns to an existing index.

  • inplace: Returns the boolean value, default value False.

It is used to modify the DataFrame in place. We don’t need to create a new object.

  • verify_integrity: Returns the boolean value, default value False.

It checks the new index for duplicate values. Otherwise, it will defer the check until necessary. It also set it to False that will improve the performance of this method.

Returns:

It will change the row labels as the output.

Example1:

This example shows how to set the index:

Output:

NameAgeid  0William32105  1Phill38132  2Parker41134  3Smith36127  

Now, we have to set the index to create the ‘month’ column:

Output:

         Age  id  Name  William  32  105  Phill    38  132  Parker   41  134  Smith    36  127  

Example2:

Create a MultiIndex using columns ‘Age’ and ‘Name’:

Output:

Nameid  Age  32William105  38Phill132  41Parker134  36Smith127  

Example3:

It creates a MultiIndex using an Index and a column:

Output:

Ageid  Name  1William32105  2Phill38132  3Parker41134  4Smith36127  

Example4:

Create a MultiIndex using two Series:

Output:

NameAgeid  11William32105  24Phill38132  39Parker41134  416Smith36127  

Next TopicPandas NumPy

You may also like