给出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
类应该可以在没有回到列表的情况下完成它。)
答案 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