一系列布尔值为Tru的输出

2024-05-17 05:42:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样的系列

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

有没有一种方法可以巧妙地把真实的地方的名字提取出来,留在熊猫或小矮人的身体里,而不必回到普通的Python身上

目前我正在使用:

sdict = s.to_dict()
for item in list(sdict):
    if sdict[item] == True:
        print (item, end=" ")

>> b d

Tags: to方法falsetruefor地方item名字
1条回答
网友
1楼 · 发布于 2024-05-17 05:42:24

^{}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')

相关问题 更多 >