How to select columns from list in Pandas

To select columns from a pandas dataframe, you can use the square bracket notation [] and pass the column names as a list inside it. Here’s an example:

Suppose you have a dataframe named df and you want to select two columns, “column1” and “column2”, you can do it like this:

selected_cols = ["column1", "column2"]
df_selected = df[selected_cols]

This will create a new dataframe df_selected that only contains the columns “column1” and “column2” from the original dataframe df.

If you want to select all columns except for a few, you can use the drop method. For example, if you want to drop the “column3” and “column4” from the dataframe df, you can do it like this:

cols_to_drop = ["column3", "column4"]
df_selected = df.drop(cols_to_drop, axis=1)

This will create a new dataframe df_selected that contains all columns from the original dataframe df, except for “column3” and “column4”. Note that the axis=1 parameter is used to specify that we are dropping columns (as opposed to rows).

Leave a Reply