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.
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
Asked: 2021-10-11 11:00:00 +0000
Seen: 13 times
Last updated: Jun 14 '22
How can I set up Gunicorn with a Django Project?
Looking for a Python Module that finds Tags for a Text describing its Content
Need a Function in Python to remove entries less than 2 digits from an Array
How can I convert a Document in Python?
How can I program a Loop in Python?
How can I enable Python Code Highlighting in Askbot?