获取值为真的系列的索引

时间:2019-01-31 04:30:07

标签: python pandas

如何仅选择True值?

myindex=['a', 'b', 'c' , 'd']
myseries=pd.Series([True, True, False, True], index=myindex)

a     True
b     True
c    False
d     True
dtype: bool

我尝试过的事情:

myseries.where(myseries == True)

这包括“ c”,而我需要返回a,b和d的列表

5 个答案:

答案 0 :(得分:4)

如果你只是想返回其是,B,C,d你的情况使用index属性的索引:

myindex=['a', 'b', 'c' , 'd']
myseries=pd.Series([True, True, False, True], index=myindex)

a     True
b     True
c    False
d     True
dtype: bool

myseries[myseries].index
>> Index(['a', 'b', 'd'], dtype='object')

如果你想把它当作一个列表:

myseries[myseries].index.tolist()
>> ['a', 'b', 'd']

答案 1 :(得分:3)

代码myseries[myseries]返回

a    True
b    True
d    True
dtype: bool

如果你特别希望的[ 'A', 'B', 'd']然后可以将其由list(myseries[myseries].index)

的列表

答案 2 :(得分:3)

修正您的代码

myseries.where(myseries).dropna().index
Index(['a', 'b', 'd'], dtype='object')

答案 3 :(得分:3)

gray = cv2.cvtColor(roi , cv2.COLOR_BGR2GRAY) bw = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\ cv2.THRESH_BINARY,11,2) kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (1, 5)) bw = cv2.morphologyEx(bw, cv2.MORPH_OPEN, kernel) _, contours , _ = cv2.findContours(bw, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE) 过滤索引值:

Series

如果性能很重要,请将它们都转换为numpy数组,然后进行过滤:

print (myseries.index[myseries].tolist())
['a', 'b', 'd']

性能

print (myseries.index.values[myseries.values].tolist())
['a', 'b', 'd']

另一个答案:

np.random.seed(456)

myindex=np.random.randint(100, size=10000).astype(str)
myseries=pd.Series(np.random.choice([True, False], size=10000), index=myindex)
print (myseries)

In [7]: %timeit (myseries.index[myseries].tolist())
178 µs ± 5.5 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [8]: %timeit (myseries.index.values[myseries.values].tolist())
113 µs ± 762 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

答案 4 :(得分:2)

您可以使用list-comrehension

import pandas as pd 

myindex=['a', 'b', 'c' , 'd']
myseries=pd.Series([True, True, False, True], index=myindex)
vals = [i for i,j in myseries.items() if j==True]
print(vals)

输出:

 ['a', 'b', 'd']