python - pandas bool 值系列为 True 的输出

标签 python pandas series

我有一个这样创建的系列

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 indexings.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/

相关文章:

python - 我想计算 Pandas DataFrame 中每一列的具体数字?

python - Pandas 对字符串 isin 列表的负选择给出了错误的结果

python - 有没有办法为 pandas groupby 对象保留每个组的子集?

python - python 写入 csv 文件的第二列

python - 如何将python 3.4.3脚本编译为exe?

python - 根据条件加权求和

sqlite - Pandas/iPython 笔记本(Jupyter)中 DataFrame/table 中的 GROUP BY 行?

python - Pandas Apply 函数引用列名

python - 每行的 Pandas 有条件替换

python - 当您使用 Python 的 Paramiko 库进行 SSH 并从远程计算机的 CLI 获取输出时,是否有一种简单的方法可以消除垃圾值?