Get column index from column name in python pandas Get column index from column name in python pandas python python

Get column index from column name in python pandas


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.columnsOut[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.


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]


DSM's solution works, but if you wanted a direct equivalent to which you could do (df.columns == name).nonzero()


matomo