Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Column selection can be performed on a pandas dataframe using a list containing the names of the desired columns by passing the list of column names inside square brackets as shown below:

import pandas as pd

# create a sample dataframe
df = pd.DataFrame({'Name': ['Alice', 'Bob', 'Charlie'],
                   'Age': [25, 30, 35],
                   'City': ['New York', 'Los Angeles', 'Chicago']})

# select columns using a list of column names
selected_columns = ['Name', 'City']
df_selected = df[selected_columns]

print(df_selected)

Output:

      Name         City
0    Alice     New York
1      Bob  Los Angeles
2  Charlie      Chicago

In the above example, the columns 'Name' and 'City' are selected using the list 'selected_columns'. The resulting dataframe contains only the selected columns.