Python Pandas-为什么“ in”运算符只处理索引而不处理数据?
我发现了Pandasin
运算符应用于Series
索引而不是实际数据的困难方式:
In [1]: import pandas as pd
In [2]: x = pd.Series([1, 2, 3])
In [3]: x.index = [10, 20, 30]
In [4]: x
Out[4]:
10 1
20 2
30 3
dtype: int64
In [5]: 1 in x
Out[5]: False
In [6]: 10 in x
Out[6]: True
我的直觉是该x
系列包含数字1而不是索引10,这显然是错误的。此行为背后的原因是什么?以下方法是最好的替代方法吗?
In [7]: 1 in set(x)
Out[7]: True
In [8]: 1 in list(x)
Out[8]: True
In [9]: 1 in x.values
Out[9]: True
更新
我对建议做了一些安排。看来x.values
是最好的方法:
In [21]: x = pd.Series(np.random.randint(0, 100000, 1000))
In [22]: x.index = np.arange(900000, 900000 + 1000)
In [23]: x.tail()
Out[23]:
900995 88999
900996 13151
900997 25928
900998 36149
900999 97983
dtype: int64
In [24]: %timeit 36149 in set(x)
10000 loops, best of 3: 190 µs per loop
In [25]: %timeit 36149 in list(x)
1000 loops, best of 3: 638 µs per loop
In [26]: %timeit 36149 in (x.values)
100000 loops, best of 3: 6.86 µs per loop
-
pandas.Series
将a视为类似于字典的字典可能会有所帮助,其中的index
值等于keys
。比较:>>> d = {'a': 1} >>> 1 in d False >>> 'a' in d True
与:
>>> s = pandas.Series([1], index=['a']) >>> 1 in s False >>> 'a' in s True
但是,请注意,对系列进行迭代将对进行迭代
data
,而不是对进行迭代index
,因此list(s)
将得出[1]
not['a']
。确实,根据文档,
index
值 “必须是唯一的且 可哈希化 ”
,所以我猜想那里下面有一个哈希表。