To select multiple columns in a Pandas DataFrame, you can pass a list of column names to the indexing operator '[]'. Here are a few examples:
1. Selecting multiple columns by name:import pandas as pd # create a sample DataFrame df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}) # select columns A and B df_AB = df[['A', 'B']] print(df_AB)
A B 0 1 4 1 2 5 2 3 6
2. Selecting multiple columns by index:
# select the first and third columns df_13 = df.iloc[:, [0, 2]] print(df_13)
A C 0 1 7 1 2 8 2 3 9
# select columns A and B using a slice df_AB_slice = df.loc[:, 'A':'B'] print(df_AB_slice)This will output:
A B 0 1 4 1 2 5 2 3 6
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.