Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get column index from label in a data frame

Tags:

r

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')?

like image 605
Leo Avatar asked Dec 13 '10 09:12

Leo


People also ask

How do you get the index of a column in a DataFrame?

You can get the column index from the column name in Pandas using DataFrame. columns. get_loc() method.

How can I get column names from a DataFrame using index?

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.

How do you select an index from a data frame?

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.


2 Answers

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".

like image 69
Henrik Avatar answered Oct 07 '22 22:10

Henrik


The following will do it:

which(colnames(df)=="B") 
like image 29
NPE Avatar answered Oct 08 '22 00:10

NPE