How to Select Multiple Columns in a Pandas Dataframe?

python

To select multiple columns in a Pandas dataframe, you can pass a list of column names to the indexing operator []:

import pandas as pd

# create sample dataframe
data = {
    'name': ['Alice', 'Bob', 'Charlie'],
    'age': [25, 30, 35],
    'gender': ['F', 'M', 'M'],
    'height': [160, 175, 180]
}
df = pd.DataFrame(data)

# select specific columns
subset = df[['name', 'age', 'gender']]
print(subset)

Output:

      name  age gender
0    Alice   25      F
1      Bob   30      M
2  Charlie   35      M

Latest Questions

python How to Fix ""zsh: command not found: python" Error on MacOS X? python How to Fix "xlrd.biffh.XLRDError: Excel xlsx file; not supported" Error in Pandas? python How to Remove All Whitespace From a Python String?