简体   繁体   English

在熊猫数据框中按组分组数据

[英]Subset data by group within pandas dataframe

I need to subset a dataframe using groups and three conditional rules. 我需要使用组和三个条件规则对数据框进行子集化。 If within a group all values in the Value column are none, I need to retain the first row for that group. 如果组中“值”列中的所有值都不为零,则需要保留该组的第一行。 If within a group all values in the Value column are not none, I need to retain all the values. 如果在一个组中,“值”列中的所有值都不是无,则需要保留所有值。 If within a group some of the values in the Value column are none and others not none, I need to drop all rows where there is a none. 如果在组中“值”列中的某些值不存在,而其他值则不存在,则需要删除所有不存在的行。 Columns Region and ID together define a unique group within the dataframe. 区域和ID列共同定义了数据框内的唯一组。

My first approach was to separate the dataframe into two chunks. 我的第一种方法是将数据帧分为两个块。 The first chunk is rows where for a group there are all nulls. 第一个块是行,其中对于一个组,所有行都为空。 The second chunk is everything else. 第二块是其他所有内容。 For the chunk of data where rows for a group contained all nulls, I would create a rownumber using a cumulative count of rows by group and query rows where the cumulative count = 1. For the second chunk, I would drop all rows where Value is null. 对于一组行包含所有空值的数据块,我将使用按组的行的累积计数创建行号,并查询累积计数= 1的行。对于第二块,我将删除Value为空值。 Then I would append the dataframes. 然后,我将追加数据帧。

Sample source dataframe 样本源数据框

dfInput = pd.DataFrame({
'Region':     [1, 1, 2, 2, 2, 2, 2],
'ID':     ['A', 'A', 'B', 'B', 'B', 'A', 'A'],
'Value':[0, 1, 1, None, 2, None, None],
})

Desired output dataframe: 所需的输出数据帧:

dfOutput = pd.DataFrame({
'Region':     [1, 1, 2, 2, 2],
'ID':     ['A', 'A', 'B', 'B', 'A'],
'Value':[0, 1, 1, 2, None],
})

Just follow your logic and using groupby 只需遵循您的逻辑并使用groupby

dfInput.groupby(['Region','ID']).Value.apply(lambda x : x.head(1) if x.isnull().all() else x.dropna()).\
        reset_index(level=[0,1]).sort_index()
Out[86]: 
   Region ID  Value
0       1  A    0.0
1       1  A    1.0
2       2  B    1.0
4       2  B    2.0
5       2  A    NaN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM