我有一个这样创建的系列
s = pd.Series({'a': False, 'b': True, 'c': False, 'd': True, 'e': False})
>> s
a False
b True
c False
d True
e False
dtype: bool
有没有一种方法可以整齐地提取 True 的名称,保留在 Pandas 或 NumPy 中,而不返回到普通的 Python?
目前我正在使用这个:
sdict = s.to_dict()
for item in list(sdict):
if sdict[item] == True:
print (item, end=" ")
>> b d
最佳答案
使用boolean indexing
与s.index
:
print (s.index[s])
Index(['b', 'd'], dtype='object')
print (s.index[s].tolist())
['b', 'd']
print (', '.join(s.index[s]))
b, d
使用np.where
有点过于复杂的解决方案,为了好玩:
print (s.index[np.where(s)[0]])
Index(['b', 'd'], dtype='object')
关于python - pandas bool 值系列为 True 的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48400760/