过滤值的访问索引

时间:2019-01-26 10:47:26

标签: python pandas

在这里我根据谓词访问序列的值:

import numpy as np

s = pd.Series(np.array([1,2,3]))
print(type(s))

print([i for i in s if i > 2])

返回:

<class 'pandas.core.series.Series'>
[3]

如何访问与谓词匹配的值的索引,因此在这种情况下,索引为2

1 个答案:

答案 0 :(得分:1)

boolean indexingindex一起使用:

print (s.index[s > 2])
#alternative
#print (s[s > 2].index)
Int64Index([2], dtype='int64')

您的解决方案应使用Series.items进行更改:

print([k for k, v in s.items() if v > 2])
[2]

性能在较大数据中有所不同:

np.random.seed(45)
s = pd.Series(np.random.randint(5, size=100000))

#print (s)

In [93]: %timeit ([k for k, v in s.items() if v > 2])
13.3 ms ± 768 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [94]: %timeit (s.index[s > 2])
930 µs ± 12.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [95]: %timeit (s[s > 2].index)
1.74 ms ± 26.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [96]: %timeit (s.index[s.values > 2])
742 µs ± 79.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [97]: %timeit (s.index.values[s.values > 2])
647 µs ± 12.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [98]: %timeit (s[s.values > 2].index.values)
1.51 ms ± 12.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)