Get column index from column name of a given Pandas DataFrame
Last Updated :
26 Jul, 2020
In this article we will see how to get column index from column name of a Dataframe. We will use Dataframe.columns attribute and Index.get_loc method of pandas module together.
Syntax: DataFrame.columns
Return: column names index
Syntax: Index.get_loc(key, method=None, tolerance=None)
Return: loc : int if unique index, slice if monotonic index, else mask
Code: Let’s create a Dataframe:
Python3
import pandas as pd
record = {'Math': [10, 20, 30,
40, 70],
'Science': [40, 50, 60,
90, 50],
'English': [70, 80, 66,
75, 88]}
df = pd.DataFrame(record)
print(df)
Output:
Dataframe
Example 1: Get a index number of “Science” column.
Python3
import pandas as pd
record = {'Math': [10, 20, 30, 40, 70],
'Science': [40, 50, 60, 90, 50],
'English': [70, 80, 66, 75, 88]}
col_name = "Science"
index_no = df.columns.get_loc(col_name)
print("Index of {} column in given dataframe is : {}".format(col_name, index_no))
Output :
index number of Science column
Example 2: Get a index number of “English” column.
Python3
import pandas as pd
record = {'Math': [10, 20, 30,
40, 70],
'Science': [40, 50, 60,
90, 50],
'English': [70, 80, 66,
75, 88]}
df = pd.DataFrame(record)
col_name = "English"
index_no = df.columns.get_loc(col_name)
print("Index of {} column in given dataframe is : {}".format(col_name, index_no))
Output :
index number of English column
Like Article
Suggest improvement
Share your thoughts in the comments
Add Your Comment
Please Login to comment...