在Python中基于布尔列过滤数据

问题描述 投票:0回答:3

我有以下 pandas 数据框,我想要一个函数返回 ID 的数据,其中

bool_1
中至少有 1 个真值,
bool_2
中至少有 2 个真值,
bool_3
列中有 3 个真值,使用
groupby 
功能。

index  ID  bool_1  bool_2  bool_3
 0      7   True    True    True    
 1      7   False   True    True
 2      7   False   False   True
 3      8   True    True    True
 4      8   True    True    True    
 5      8   False   False   True    
 6      9   True    True    True    
 7      9   True    False   True    
 8      9   True    False   True    
 9      9   True    False   False   

作为输出,我希望返回

ID
7
8
的完整数据,因为
9
对于
bool_2
只有 1 个真实值。 对这个功能有什么想法吗?谢谢!

python pandas group-by filtering
3个回答
1
投票

以下功能可能有效:

def filter_dataframe(df):
    # Group by ID and calculate the sum of True values in each column
    grouped_df = df.groupby('ID').agg({
        'bool_1': 'sum',
        'bool_2': 'sum',
        'bool_3': 'sum'
    })

    # Filter rows based on the conditions
    filtered_df = grouped_df[(grouped_df['bool_1'] >= 1) & (grouped_df['bool_2'] >= 2) & (grouped_df['bool_3'] >= 3)]

    # Get the corresponding IDs
    selected_ids = filtered_df.index

    # Filter the original dataframe based on the selected IDs
    result_df = df[df['ID'].isin(selected_ids)]

    return result_df

1
投票

您可以在字典中指定

True
的数量,因此可以通过
DataFrame.ge
进行比较,通过聚合总和来比较
True
的数量,并通过
DataFrame
过滤原始 boolean indexing
 Series.isin

d = {'bool_1':1, 'bool_2':2,'bool_3':3}

ids = df.groupby('ID')[list(d.keys())].sum().ge(d).all(axis=1)
print (ids)
ID
7     True
8     True
9    False
dtype: bool

out = df[df['ID'].isin(ids.index[ids])]
print (out)
   index  ID  bool_1  bool_2  bool_3
0      0   7    True    True    True
1      1   7   False    True    True
2      2   7   False   False    True
3      3   8    True    True    True
4      4   8    True    True    True
5      5   8   False   False    True

另一个想法:

d = {'bool_1':1, 'bool_2':2,'bool_3':3}

mask = df.groupby('ID')[list(d.keys())].transform('sum').ge(d).all(axis=1)
print (mask)
0     True
1     True
2     True
3     True
4     True
5     True
6    False
7    False
8    False
9    False
dtype: bool

out = df[mask]
print (out)
   index  ID  bool_1  bool_2  bool_3
0      0   7    True    True    True
1      1   7   False    True    True
2      2   7   False   False    True
3      3   8    True    True    True
4      4   8    True    True    True
5      5   8   False   False    True

0
投票

这是一个简单的groupby,带有sum聚合功能,然后你可以使用任何你喜欢的过滤方法。

实现这一目标的一个非常简短的方法是:

df.groupby('ID')[['bool_1', 'bool_2', 'bool_3']].sum().query('bool_1>0 & bool_2>1 & bool_3>2')

这会给你:

ID | bool_1 | bool_2 | bool_3
7  |   1    |   2    |   3
8  |   2    |   2    |   3
© www.soinside.com 2019 - 2024. All rights reserved.