Python | Pandas DataFrame.set_index()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas set_index() is a method to set a List, Series or Data frame as index of a Data Frame. Index column can be set while making a data frame too. But sometimes a data frame is made out of two or more data frames and hence later index can be changed using this method.
DataFrame.set_index(keys, drop=True, append=False, inplace=False, verify_integrity=False)
keys: Column name or list of column name.
drop: Boolean value which drops the column used for index if True.
append: Appends the column to existing index column if True.
inplace: Makes the changes in the dataframe if True.
verify_integrity: Checks the new index column for duplicates if True.
To download the CSV file used, Click Here.
Code #1: Changing Index column
In this example, First Name column has been made the index column of Data Frame.
As shown in the output images, earlier the index column was a series of number but later it has been replaced with First name.
Before operation –
After operation –
Code #2: Multiple index Column
In this example, two columns will be made as index column. Drop parameter is used to Drop the column and append parameter is used to append passed columns to the already existing index column.
As shown in the output Image, the data is having 3 index columns.
Code #3: Setting a single Float column as Index in Pandas DataFrame
In the above example, we set the column ‘Agg_Marks‘ as an index of the data frame.
Code #4: Setting three columns as MultiIndex in Pandas DataFrame
In the above example, we set the columns ‘Name‘, ‘City‘, and ‘ID‘ as multiIndex of the data frame.