sds sds - 2 months ago 9
Python Question

How do I get the index of a column by name?

Given a

DataFrame


>>> df
x y z
0 1 a 7
1 2 b 5
2 3 c 7


I would like to find the index of the column by name, e.g.,
x
-> 0,
z
-> 2, &c.

I can do

>>> list(df.columns).index('y')
1


but it seems backwards (the
pandas.indexes.base.Index
class should probably be able to do it without circling back to list).

Answer

You can use Index.get_loc:

print (df.columns.get_loc('z'))
2

Another solution with Index.searchsorted:

print (df.columns.searchsorted('z'))
2

Timings:

In [86]: %timeit (df.columns.get_loc('z'))
The slowest run took 13.42 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 1.99 µs per loop

In [87]: %timeit (df.columns.searchsorted('z'))
The slowest run took 10.46 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 4.48 µs per loop
Comments