Ask Your Question
0

How can column selection be performed on a pandas dataframe using a list containing the names of the desired columns in Python?

asked 2021-10-11 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-06-14 10:00:00 +0000

plato gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-10-11 11:00:00 +0000

Seen: 13 times

Last updated: Jun 14 '22