To select multiple columns in a Pandas dataframe, you can use the loc
method and specify the column names you want to select, separated by a comma. This will return a new dataframe with only the selected columns.
Here's an example of using the loc
method to select multiple columns in a Pandas dataframe:
import pandas as pd
# create a sample dataframe
df = pd.DataFrame({"A": [1, 2, 3],
"B": [4, 5, 6],
"C": [7, 8, 9]})
# select the A and C columns
df_selected = df.loc[:, ["A", "C"]]
# display the result
print(df_selected)
This will select the A
and C
columns from the dataframe and return a new dataframe with only these columns. The resulting dataframe will be displayed to the console.
The output will be:
A C
0 1 7
1 2 8
2 3 9
You can also use the iloc
method to select multiple columns in a Pandas dataframe, by specifying the column indices you want to select, separated by a comma.
For example:
# select the first and third columns (using their indices)
df_selected = df.iloc[:, [0, 2]]
# display the result
print(df_selected)
A C
0 1 7
1 2 8
2 3 9
This will select the first and third columns from the dataframe, based on their indices, and return a new dataframe with only these columns.
The resulting dataframe will be displayed to the console. The output will be the same as in the previous example.
Related tutorials curated for you
What does Head() do in Pandas?
How to GroupBy Index in Pandas
How to get the first row in Pandas
How to calculate the standard deviation in Pandas DataFrame
How to find the minimum in Pandas
How to find the mode in a Pandas DataFrame
How to use where() in Pandas
How to convert a series to a list in Pandas
How to calculate covariance in Pandas
How to convert string to float in Pandas
How to join two DataFrames in Pandas
How to normalize a column in Pandas