How to get column index from column name in Python Pandas?

PythonServer Side ProgrammingProgramming

To get column index from column name in Python Pandas, we can use the get_loc() method.

Steps −

  • Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
  • Print the input DataFrame, df.
  • Find the columns of DataFrame, using df.columns.
  • Print the columns from Step 3.
  • Initialize a variable column_name.
  • Get the location, i.e., of index for column_name.
  • Print the index of the column_name.

Example −

import pandas as pd

df = pd.DataFrame(
   {
      "x": [5, 2, 7, 0],
      "y": [4, 7, 5, 1],
      "z": [9, 3, 5, 1]
   }
)

print"Input DataFrame 1 is:\n", df
columns = df.columns
print"Columns in the given DataFrame: ", columns

column_name = "z"
column_index = columns.get_loc(column_name)
print"Index of the column ", column_name, " is: ", column_index

column_name = "x"
column_index = columns.get_loc(column_name)
print"Index of the column ", column_name, " is: ", column_index

column_name = "y"
column_index = columns.get_loc(column_name)
print"Index of the column ", column_name, " is: ", column_index

Output

Input DataFrame 1 is:
x y z
0 5 4 9
1 2 7 3
2 7 5 5
3 0 1 1

Columns in the given DataFrame: Index(['x', 'y', 'z'],
dtype='object')

Index of the column z is: 2
Index of the column x is: 0
Index of the column y is: 1
raja
Published on 14-Sep-2021 11:42:31
Advertisements