【问题标题】:boolean operation with groupby in pandas大熊猫中 groupby 的布尔运算
【发布时间】:2017-08-14 01:01:44
【问题描述】:

我想以特定方式使用pandas.groupby。给定一个带有两个布尔列(称为 col1col2)和一个 id 列的 DataFrame,我想通过以下方式添加一个列:

对于每个条目,如果 (col2 为 True) 并且 (col1 对于任何具有相同 id 的条目为 True) 则分配 True。否则为假。

我做了一个简单的例子:

df = pd.DataFrame([[0,1,1,2,2,3,3],[False, False, False, False, False, False, True],[False, True, False, False, True ,True, False]]).transpose()
df.columns = ['id', 'col1', 'col2']

给出以下DataFrame

     id   col1   col2
0    0   False   False
1    1   False   True
2    1   False   False
3    2   False   False
4    2   False   True
5    3   False   True
6    3   True    False

根据上述规则,应添加以下应该列:

0    False
1    False
2    False
3    False
4    False
5     True
6    False

有什么优雅的方法可以做到这一点吗?

【问题讨论】:

    标签: python python-3.x pandas dataframe pandas-groupby


    【解决方案1】:

    此代码将产生您请求的输出:

    df2 = df.merge(df.groupby('id')['col1'] # group on "id" and select 'col1'
                        .any()              # True if any items are True
                        .rename('cond2')    # name Series 'cond2'
                        .to_frame()         # make a dataframe for merging
                        .reset_index())     # reset_index to get id column back
    print(df2.col2 & df2.cond2)             # True when 'col2' and 'cond2' are True
    

    【讨论】:

      【解决方案2】:
      df.groupby('id').col1.transform('any') & df.col2
      
      0    False
      1    False
      2    False
      3    False
      4    False
      5     True
      6    False
      dtype: bool
      

      【讨论】:

        猜你喜欢
        • 2018-03-17
        • 1970-01-01
        • 1970-01-01
        • 2019-02-24
        • 1970-01-01
        • 2017-05-05
        • 1970-01-01
        • 2022-07-05
        • 2017-10-05
        相关资源
        最近更新 更多