我想识别所有行,其中 5 列中的 4 列为 True,即
df = pd.DataFrame(
[
[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 0],
[0, 0, 0, 0, 0],
[1, 1, 1, 0, 1],
],
index=["abc", "def", "ghi", "jkl", "mnl"],
columns=list("abcde")
).applymap(bool)
所以......
df = pd.DataFrame(
[
[1, 1, 1, 1, 0],
[1, 1, 1, 0, 1],
],
index=["ghi", "mnl"],
columns=list("abcde")
).applymap(bool)
我该如何解决这个问题?
最佳答案
使用列的 sum
并按值的数量进行比较,此处 4
与 Series.eq
并按boolean indexing
过滤:
print (df[df.sum(axis=1).eq(4)])
a b c d e
ghi True True True True False
mnl True True True False True
详细信息:
print (df.sum(axis=1))
abc 0
def 5
ghi 4
jkl 0
mnl 4
dtype: int64
如果想要 4
或 5
匹配 True:
print (df[df.sum(axis=1).isin([4,5])])
a b c d e
def True True True True True
ghi True True True True False
mnl True True True False True
如果想要大于或等于 4:
print (df[df.sum(axis=1).ge(4)])
a b c d e
def True True True True True
ghi True True True True False
mnl True True True False True
关于python - 根据等于 True 的列数选择数据框中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59948932/