如何按名称获取列的索引?

时间:2016-09-11 17:59:41

标签: python python-2.7 pandas

给出DataFrame

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

我想按名称找到列的索引,例如x - > 0,z - > 2,& c。

我能做到

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

但它似乎倒退了(pandas.indexes.base.Index类应该可以在没有回到列表的情况下完成它。)

1 个答案:

答案 0 :(得分:1)

您可以使用Index.get_loc

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

Index.searchsorted的另一个解决方案:

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

<强>计时

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