Getting multiple columns in Pandas DataFrame
Start your free 7-days trial now!
To get multiple columns in Pandas, use either:
Consider the following DataFrame:
df
A B C0 3 5 71 4 6 8
Using square-brackets directly
To get columns A
and B
as a DataFrame:
cols = df[["A","B"]]cols
A B0 3 51 4 6
Since a copy is returned here, modifying cols
would not mutate the original df
, as demonstrated by:
df
A B C0 3 5 71 4 6 8
Here, we're using the iat
property to modify the top-left entry of cols
.
Getting multiple columns using labels
To get multiple columns using their column labels, use loc
like so:
cols
A C0 3 71 4 8
The :
before the comma indicates that we want to fetch all the rows. Similar to the []
case, a copy is returned here, so modifying this will not mutate the original df
.
Getting multiple columns using integer index
To get multiple columns using integer indices, use iloc
like so:
B C0 5 71 6 8
The :
before the comma indicates that we want to fetch all the rows. Again, a copy of the data is returned here, so modifying this will not mutate the original df
.