Get column index from column name of a given Pandas DataFrame



Get column index from column name of a given Pandas DataFrame

 

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:

# import pandas library
import pandas as pd
 
# dictionary
record = {'Math': [10, 20, 30
                   40, 70],
          'Science': [40, 50, 60,
                      90, 50], 
          'English': [70, 80, 66
                      75, 88]}
 
# create a dataframe
df = pd.DataFrame(record)
 
# show the dataframe
print(df)

Output:

Dataframe

Dataframe

Example 1: Get a index number of “Science” column.

# import pandas library
import pandas as pd
 
# dictionary
record = {'Math': [10, 20, 30, 40, 70],
          'Science': [40, 50, 60, 90, 50], 
          'English': [70, 80, 66, 75, 88]}
 
# give column name
col_name = "Science"
 
# find the index no
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

index number of Science column

Example 2: Get a index number of “English” column.

# import pandas library
import pandas as pd
 
# dictionary
record = {'Math': [10, 20, 30,
                   40, 70],
          'Science': [40, 50, 60,
                      90, 50], 
          'English': [70, 80, 66,
                      75, 88]}
 
# create a dataframe
df = pd.DataFrame(record)
 
# give column name
col_name = "English"
 
# find the index no
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

 

Last Updated on August 30, 2021 by admin

Leave a Reply

Your email address will not be published. Required fields are marked *

Recommended Blogs