How to Select Columns by Name in Pandas (3 Examples)


You can use the following methods to select columns by name in a pandas DataFrame:

Method 1: Select One Column by Name

df.loc[:, 'column1']

Method 2: Select Multiple Columns by Name

df.loc[:, ['column1', 'column3', 'column4']] 

Method 3: Select Columns in Range by Name

df.loc[:, 'column2':'column4'] 

The following examples show how to use each of these methods in practice with the following pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'mavs': [10, 12, 14, 15, 19, 22, 27],
                   'cavs': [18, 22, 19, 14, 14, 11, 20],
                   'hornets': [5, 7, 7, 9, 12, 9, 14],
                   'spurs': [10, 12, 14, 13, 13, 19, 22],
                   'nets': [10, 14, 25, 22, 25, 17, 12]})

#view DataFrame
print(df)

   mavs  cavs  hornets  spurs  nets
0    10    18        5     10    10
1    12    22        7     12    14
2    14    19        7     14    25
3    15    14        9     13    22
4    19    14       12     13    25
5    22    11        9     19    17
6    27    20       14     22    12

Example 1: Select One Column by Name

The following code shows how to select the ‘spurs’ column in the DataFrame:

#select column with name 'spurs'
df.loc[:, 'spurs']

0    10
1    12
2    14
3    13
4    13
5    19
6    22
Name: spurs, dtype: int64

Only the values from the ‘spurs’ column are returned.

Example 2: Select Multiple Columns by Name

The following code shows how to select the cavs, spurs, and nets columns in the DataFrame:

#select columns with names cavs, spurs, and nets
df.loc[:, ['cavs', 'spurs', 'nets']]

        cavs	spurs	nets
0	18	10	10
1	22	12	14
2	19	14	25
3	14	13	22
4	14	13	25
5	11	19	17
6	20	22	12

Only the values from the cavs, spurs, and nets columns are returned.

Example 3: Select Columns in Range by Name

The following code shows how to select all columns between the names ‘hornets’ and ‘nets’ in the DataFrame:

#select all columns between hornets and nets
df.loc[:, 'hornets':'nets']

        hornets	spurs	nets
0	5	10	10
1	7	12	14
2	7	14	25
3	9	13	22
4	12	13	25
5	9	19	17
6	14	22	12

All of the columns between the names ‘hornets’ and ‘nets’ are returned.

Additional Resources

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

Pandas: How to Move Column to Front of DataFrame
Pandas: How to Check if Column Contains String
Pandas: How to Add Empty Column to DataFrame (3 Examples)

Leave a Reply

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