Say we have the following data frame:
> df A B C 1 1 2 3 2 4 5 6 3 7 8 9
We can select column 'B' from its index:
> df[,2] [1] 2 5 8
Is there a way to get the index (2) from the column label ('B')?
You can get the column index from the column name in Pandas using DataFrame. columns. get_loc() method.
Sometimes you may have an column index and wanted to get column name by index in pandas DataFrmae, you can do so by using DataFrame. columns[idx] . Note that index start from 0.
So, if you want to select the 5th row in a DataFrame, you would use df. iloc[[4]] since the first row is at index 0, the second row is at index 1, and so on. . loc selects rows based on a labeled index.
you can get the index via grep
and colnames
:
grep("B", colnames(df)) [1] 2
or use
grep("^B$", colnames(df)) [1] 2
to only get the columns called "B" without those who contain a B e.g. "ABC".
The following will do it:
which(colnames(df)=="B")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With