Index Manipulation of pandas DataFrames in Python (3 Examples)
This tutorial demonstrates how to modify the index of pandas DataFrames in the Python programming language.
Creation of Example Data
import pandas as pd # Import pandas |
import pandas as pd # Import pandas
my_df = pd.DataFrame({'A':range(11, 18), # Construct pandas DataFrame 'B':['y', 'w', 'y', 'r', 's', 's', 'y'], 'C':range(101, 108)}) print(my_df) # A B C # 0 11 y 101 # 1 12 w 102 # 2 13 y 103 # 3 14 r 104 # 4 15 s 105 # 5 16 s 106 # 6 17 y 107 |
my_df = pd.DataFrame({'A':range(11, 18), # Construct pandas DataFrame 'B':['y', 'w', 'y', 'r', 's', 's', 'y'], 'C':range(101, 108)}) print(my_df) # A B C # 0 11 y 101 # 1 12 w 102 # 2 13 y 103 # 3 14 r 104 # 4 15 s 105 # 5 16 s 106 # 6 17 y 107
Example 1: Use pandas DataFrame Column as Index
df1 = my_df.set_index('C') # Set column to index print(df1) # A B # C # 101 11 y # 102 12 w # 103 13 y # 104 14 r # 105 15 s # 106 16 s # 107 17 y |
df1 = my_df.set_index('C') # Set column to index print(df1) # A B # C # 101 11 y # 102 12 w # 103 13 y # 104 14 r # 105 15 s # 106 16 s # 107 17 y
Example 2: Resetting Index of pandas DataFrame from 0
df2 = df1.reset_index() # Reset index print(df2) # C A B # 0 101 11 y # 1 102 12 w # 2 103 13 y # 3 104 14 r # 4 105 15 s # 5 106 16 s # 6 107 17 y |
df2 = df1.reset_index() # Reset index print(df2) # C A B # 0 101 11 y # 1 102 12 w # 2 103 13 y # 3 104 14 r # 4 105 15 s # 5 106 16 s # 6 107 17 y
Example 3: Convert Index of pandas DataFrame to Column
df3 = my_df.copy() # Create copy of DataFrame df3['index'] = df3.index # Save index as column print(df3) # A B C index # 0 11 y 101 0 # 1 12 w 102 1 # 2 13 y 103 2 # 3 14 r 104 3 # 4 15 s 105 4 # 5 16 s 106 5 # 6 17 y 107 6 |
df3 = my_df.copy() # Create copy of DataFrame df3['index'] = df3.index # Save index as column print(df3) # A B C index # 0 11 y 101 0 # 1 12 w 102 1 # 2 13 y 103 2 # 3 14 r 104 3 # 4 15 s 105 4 # 5 16 s 106 5 # 6 17 y 107 6
Related Tutorials & Further Resources
In the following, you can find some additional resources on topics such as data inspection, naming data, and indices: