Problem
When retrieving a column index in R, you could do it by using the name of the column.
idx <- which(names(my_data)==my_colum_name)
Is it possible to get the same result with pandas dataframes?
Asked by ak3nat0n
Solution #1
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 require this on a regular basis. Access by name usually works for me (df[“pear”], df[[“apple”, “orange”]], or maybe df.columns.isin([“orange”, “pear”]), but I can see why you’d prefer the index number in some circumstances.
Answered by DSM
Solution #2
Here’s how to solve it using list comprehension. cols is a list of columns for which an index should be created:
[df.columns.get_loc(c) for c in cols if c in df]
Answered by snovik
Solution #3
DSM’s solution works, but you could do (df.columns == name) if you needed a direct equivalent. nonzero()
Answered by Wes McKinney
Solution #4
When you need to locate multiple column matches, you can use a vectorized solution with the searchsorted technique. An implementation would be – with df as the dataframe and query cols as the column names to be searched for.
def column_index(df, query_cols):
cols = df.columns.values
sidx = np.argsort(cols)
return sidx[np.searchsorted(cols,query_cols,sorter=sidx)]
Sample run –
In [162]: df
Out[162]:
apple banana pear orange peach
0 8 3 4 4 2
1 4 4 3 0 1
2 1 2 6 8 1
In [163]: column_index(df, ['peach', 'banana', 'apple'])
Out[163]: array([4, 1, 0])
Answered by Divakar
Solution #5
In case you want the column name from the column location (the other way around to the OP question), you can use:
>>> df.columns.get_values()[location]
Using @DSM Example:
>>> df = DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]})
>>> df.columns
Index(['apple', 'orange', 'pear'], dtype='object')
>>> df.columns.get_values()[1]
'orange'
Other ways:
df.iloc[:,1].name
df.columns[location] #(thanks to @roobie-nuby for pointing that out in comments.)
Answered by salhin
Post is based on https://stackoverflow.com/questions/13021654/get-column-index-from-column-name-in-python-pandas