在pandas中使用groupby进行布尔运算

spl*_*ter 6 python dataframe python-3.x pandas pandas-groupby

我想以pandas.groupby特定的方式使用.给定一个数据帧有两个布尔列(叫他们col1col2)和ID列,我想通过以下方式添加一列:

对于每个条目,if(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']
Run Code Online (Sandbox Code Playgroud)

给出以下内容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
Run Code Online (Sandbox Code Playgroud)

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

0    False
1    False
2    False
3    False
4    False
5     True
6    False
Run Code Online (Sandbox Code Playgroud)

有什么想法以优雅的方式做到这一点?

Cra*_*aig 5

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

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
Run Code Online (Sandbox Code Playgroud)


piR*_*red 5

df.groupby('id').col1.transform('any') & df.col2

0    False
1    False
2    False
3    False
4    False
5     True
6    False
dtype: bool
Run Code Online (Sandbox Code Playgroud)