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

我想识别所有行,其中 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)

我该如何解决这个问题?


白板的微信
浏览 87回答 1
1回答

噜噜哒

使用sum列并按值的数量进行比较,这里4使用Series.eq和过滤boolean indexing:print (df[df.sum(axis=1).eq(4)])        a     b     c      d      eghi  True  True  True   True  Falsemnl  True  True  True  False   True详情:print (df.sum(axis=1))abc    0def    5ghi    4jkl    0mnl    4dtype: int64如果想要4或5匹配 True:print (df[df.sum(axis=1).isin([4,5])])        a     b     c      d      edef  True  True  True   True   Trueghi  True  True  True   True  Falsemnl  True  True  True  False   True如果想要大于或等于 4:print (df[df.sum(axis=1).ge(4)])        a     b     c      d      edef  True  True  True   True   Trueghi  True  True  True   True  Falsemnl  True  True  True  False   True
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python