gpt4 book ai didi

python - Pandas:从数据帧返回行,其中多个列子集不为零

转载 作者:行者123 更新时间:2023-11-28 21:35:56 25 4
gpt4 key购买 nike

我有一个名为df的数据框

数据框中的列可以进行逻辑分组。因此,我将列名称分组到列表 A、B、C 中,其中:

A = [column_1, column_2, column_3]
B = [column_4, column_5, column_6]
C = [column_7, column_8, column_9]

除了 column_1column_9 列之外,df 还有一个名为 “filename_ID” 的列,它被用作索引,因此不会被分组。列 column_1column_9 仅包含 0 和 1 值。

现在我想过滤数据框,使其仅包含每组(A、B、C)至少有一个非零值的行。因此,我只想保留具有满足此条件的相应 filename_ID 的行。

我设法为每个组创建一个单独的数据框:

df_A = df.loc[(df[A]!=0).any(axis=1)]
df_B = df.loc[(df[B]!=0).any(axis=1)]
df_C = df.loc[(df[C]!=0).any(axis=1)]

但是,我不知道如何同时应用所有条件 - 即如何创建一个新的数据帧,其中所有行都满足每个逻辑列组中至少有一个非零值的条件。

最佳答案

设置

np.random.seed([3, 1415])

df = pd.DataFrame(
np.random.randint(2, size=(10, 9)),
columns=[f"col{i + 1}" for i in range(9)]
)

df

col1 col2 col3 col4 col5 col6 col7 col8 col9
0 0 1 0 1 0 0 1 0 1
1 1 1 1 0 1 1 0 1 0
2 0 0 0 0 0 0 0 0 0
3 1 0 1 1 1 1 0 0 0
4 0 0 1 1 1 1 1 0 1
5 1 1 0 1 1 1 1 1 1
6 1 0 1 0 0 0 1 1 0
7 0 0 0 0 0 1 0 1 0
8 1 0 1 0 1 0 0 1 1
9 1 0 1 0 0 1 0 1 0

解决方案

创建字典

m = {
**dict.fromkeys(['col1', 'col2', 'col3'], 'A'),
**dict.fromkeys(['col4', 'col5', 'col6'], 'B'),
**dict.fromkeys(['col7', 'col8', 'col9'], 'C'),
}

然后基于axis=1groupby

df[df.groupby(m, axis=1).any().all(1)]

col1 col2 col3 col4 col5 col6 col7 col8 col9
0 0 1 0 1 0 0 1 0 1
1 1 1 1 0 1 1 0 1 0
4 0 0 1 1 1 1 1 0 1
5 1 1 0 1 1 1 1 1 1
8 1 0 1 0 1 0 0 1 1
9 1 0 1 0 0 1 0 1 0

注意那些没有成功的

   col1  col2  col3  col4  col5  col6  col7  col8  col9
2 0 0 0 0 0 0 0 0 0
3 1 0 1 1 1 1 0 0 0
6 1 0 1 0 0 0 1 1 0
7 0 0 0 0 0 1 0 1 0

您也可以有这样的列:

cols = [['col1', 'col2', 'col3'], ['col4', 'col5', 'col6'], ['col7', 'col8', 'col9']]
m = {k: v for v, c in enumerate(cols) for k in c}

并执行相同的groupby

关于python - Pandas:从数据帧返回行,其中多个列子集不为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51755504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com