在DataFrame MultiIndex中搜索Python pandas



这是我所做的:

import pandas as pd
t = pd.DataFrame(data={'i1':[0,0,0,0,1,1,1,1,2,2,2,2],
                       'i2':[0,1,2,3,0,1,2,3,0,1,2,3],
                       'x':[1.,2.,3.,4.,5.,6.,7.,8.,9.,10.,11.,12.]})
t.set_index(['i1','i2'], inplace=True)
t.sort_index(inplace=True)
t.index.values.searchsorted( (1,1) )

这是我得到的错误:

> Traceback (most recent call last):   File "<stdin>", line 1, in
> <module> TypeError: '<' not supported between instances of 'tuple' and
> 'int'

请帮助我了解我做错了什么。

索引值是元组:type(t.index.values[0])给出正确的<class 'tuple'>,我给出作为输入来searchsorted元组。那么"元组"到"int"的比较从何而来呢?

>>> print(t)
          x
i1 i2      
0  0    1.0
   1    2.0
   2    3.0
   3    4.0
1  0    5.0
   1    6.0
   2    7.0
   3    8.0
2  0    9.0
   1   10.0
   2   11.0
   3   12.0
searchsorted不适用于

元组。github 上存在一个多数组搜索排序失败的未解决问题

关于这个问题,其中一位与会者建议使用get_indexer

使用您的代码

t.index.get_indexer([(1,1)])[0]
# outputs:
5

我找到了解决方案:

>>> t.index.get_loc( (1,1) )
5

此解决方案比使用 t.index.get_indexer 快 ~200 倍:

>>> import time
>>> time.clock()
168.56
>>> for i in range(10000): a = t.index.get_indexer([(1,1)])[0]
... 
>>> time.clock()
176.76
>>> (176.76 - 168.56) / 10000
0.0008199999999999989 # 820e-6 sec per call
>>> time.clock()
176.76
>>> for i in range(1000000): a = t.index.get_loc( (1,1) )
... 
>>> time.clock()
180.94
>>> (180.94-176.76)/1000000
4.1800000000000066e-06 # 4.2e-6 sec per call

最新更新