Pandas: How to Get Column Name by Index


You can use the following methods to get a column name by index position in pandas:

Method 1: Get One Column Name by Index Position

#get column name in index position 2
colname = df.columns[2]

Method 2: Get Multiple Column Names by Index Positions

#get column names in index positions 2 and 4
colname = df.columns[[2, 4]] 

The following examples show how to use each method in practice with the following pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
                   'points': [18, 22, 19, 14, 14, 11, 20, 28],
                   'assists': [5, 7, 7, 9, 12, 9, 9, 4],
                   'rebounds': [11, 8, 10, 6, 6, 5, 9, 12],
                   'steals': [4, 3, 3, 2, 5, 4, 3, 8],
                   'blocks': [1, 0, 0, 3, 2, 2, 1, 5]})

#view DataFrame
print(df)

  team  points  assists  rebounds  steals  blocks
0    A      18        5        11       4       1
1    B      22        7         8       3       0
2    C      19        7        10       3       0
3    D      14        9         6       2       3
4    E      14       12         6       5       2
5    F      11        9         5       4       2
6    G      20        9         9       3       1
7    H      28        4        12       8       5

Example 1: Get One Column Name by Index Position

The following code shows how to get the column name for the column in index position 2 of the DataFrame:

#get column name for column in index position 2
colname = df.columns[2]

#display column name
print(colname)

assists

The column name for the column in index position 2 is assists.

Note: Column index values start at 0 in Python. Thus, the column in index position 2 would be the third column in the DataFrame, which has the name assists.

Example 2: Get Multiple Column Names by Index Positions

The following code shows how to get the column names for the columns in index positions 2 and 4 of the DataFrame:

#get column names in index positions 2 and 4
colname = df.columns[[2, 4]] 

#display column names
print(colname)

Index(['assists', 'steals'], dtype='object')

From the output we can see:

  • The column name for the column in index position 2 is assists.
  • The column name for the column in index position 4 is steals.

Note: In this example we chose to get the column names for two columns by index position, but you can use similar syntax to retrieve the column names for as many columns as you’d like.

Additional Resources

The following tutorials explain how to perform other common tasks in pandas:

How to Get Cell Value from Pandas DataFrame
How to Rename Index in Pandas DataFrame
How to Sort Columns by Name in Pandas

Leave a Reply

Your email address will not be published.