Use Column to Set Index of pandas DataFrame in Python (Example Code)
In this article you’ll learn how to use a column of a pandas DataFrame as index in the Python programming language.
Setting up the Example
import pandas as pd # Load pandas library |
import pandas as pd # Load pandas library
my_df = pd.DataFrame({'A':range(18, 24), # Construct pandas DataFrame 'B':range(12, 6, - 1)}) print(my_df) # A B # 0 18 12 # 1 19 11 # 2 20 10 # 3 21 9 # 4 22 8 # 5 23 7 |
my_df = pd.DataFrame({'A':range(18, 24), # Construct pandas DataFrame 'B':range(12, 6, - 1)}) print(my_df) # A B # 0 18 12 # 1 19 11 # 2 20 10 # 3 21 9 # 4 22 8 # 5 23 7
Example: Apply set_index Function to Add Column as Index of pandas DataFrame
my_df = my_df.set_index('A') # Use first column as index print(my_df) # B # A # 18 12 # 19 11 # 20 10 # 21 9 # 22 8 # 23 7 |
my_df = my_df.set_index('A') # Use first column as index print(my_df) # B # A # 18 12 # 19 11 # 20 10 # 21 9 # 22 8 # 23 7
Related Articles
Please find some related Python programming language tutorials on topics such as data inspection, naming data, and indices below: