让我们看一下这个示例数据框:
df = pd.DataFrame({'ID':[1,2,3],'Col1':[True,False,False],'Col2':[False,False,False], 'Col3':[True,False,True]})
ID Col1 Col2 Col3
0 1 True False True
1 2 False False False
2 3 False False True
我想选择 df 中至少有一个 True 的行。我当然可以执行以下操作:
df[df["Col1"] | df["Col2"] | df["Col3"]]
但是我的真实数据框有很多列,并且我不知道它们的名字。请问我该怎么办?
预期输出:
ID Col1 Col2 Col3
0 1 True False True
2 3 False False True
最佳答案
您可以使用.select_dtypes
和带有.loc
的 bool 过滤
df.loc[df.select_dtypes('bool').sum(axis=1).ge(1)]
ID Col1 Col2 Col3
0 1 True False True
2 3 False False True
关于python - Pandas 选择至少一列中具有特定值的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70020936/