Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get column index from column name in python pandas

In R when you need to retrieve a column index based on the name of the column you could do

idx <- which(names(my_data)==my_colum_name) 

Is there a way to do the same with pandas dataframes?

like image 918
ak3nat0n Avatar asked Oct 22 '12 23:10

ak3nat0n


People also ask

How do you find 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. DataFrame.

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 I get specific columns in pandas?

Selecting columns based on their name This is the most basic way to select a single column from a dataframe, just put the string name of the column in brackets. Returns a pandas series. Passing a list in the brackets lets you select multiple columns at the same time.


2 Answers

Sure, you can use .get_loc():

In [45]: df = DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]})  In [46]: df.columns Out[46]: Index([apple, orange, pear], dtype=object)  In [47]: df.columns.get_loc("pear") Out[47]: 2 

although to be honest I don't often need this myself. Usually access by name does what I want it to (df["pear"], df[["apple", "orange"]], or maybe df.columns.isin(["orange", "pear"])), although I can definitely see cases where you'd want the index number.

like image 69
DSM Avatar answered Sep 21 '22 17:09

DSM


Here is a solution through list comprehension. cols is the list of columns to get index for:

[df.columns.get_loc(c) for c in cols if c in df] 
like image 43
snovik Avatar answered Sep 20 '22 17:09

snovik