Identify Column Indices in pandas DataFrame in Python (Example Code)
In this Python programming tutorial you’ll learn how to return the index of a certain variable in a pandas DataFrame.
Setting up the Example
import pandas as pd # Load pandas library |
import pandas as pd # Load pandas library
my_df = pd.DataFrame({'A':[1, 2, 9, 2, 1, 2, 7], # Construct example DataFrame 'B':[5, 3, 8, 7, 1, 9, 2], 'C':[8, 2, 5, 7, 1, 2, 6]}) print(my_df) # Display example DataFrame in console # A B C # 0 1 5 8 # 1 2 3 2 # 2 9 8 5 # 3 2 7 7 # 4 1 1 1 # 5 2 9 2 # 6 7 2 6 |
my_df = pd.DataFrame({'A':[1, 2, 9, 2, 1, 2, 7], # Construct example DataFrame 'B':[5, 3, 8, 7, 1, 9, 2], 'C':[8, 2, 5, 7, 1, 2, 6]}) print(my_df) # Display example DataFrame in console # A B C # 0 1 5 8 # 1 2 3 2 # 2 9 8 5 # 3 2 7 7 # 4 1 1 1 # 5 2 9 2 # 6 7 2 6
Example: Find Index Position of Variable in pandas DataFrame
print(my_df.columns.get_loc("B")) # Identify index position of column # 1 |
print(my_df.columns.get_loc("B")) # Identify index position of column # 1