python - 根据等于 True 的列数选择数据框中的行

标签 python pandas dataframe

我想识别所有行,其中 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 并按值的数量进行比较,此处 4Series.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

如果想要 45 匹配 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/

相关文章:

python - Anaconda 导航器仅显示一个 Python 版本

python - 将单个值从一列复制到满足条件的另一列

python - 在数据框中创建变量作为另一个数据框中其他变量和值的函数的快速方法?

r - 绑定(bind)具有不同行数的列

python - 如何一次转换多个 Spark 数据框列类型?

python - 我怎样才能每小时执行一次Python代码

python-3.x - Pandas 过滤器与 loc 方法

python - 在不同条件下向 pandas Dataframe 添加列

python - *有效地*使用 RPy(或其他方式)将数据帧从 Pandas 移动到 R

python - 从 cron 表达式创建 apscheduler 作业触发器