Pandas Create Column with Groupby and Sum with additional condition
<p>I'm trying to add a new column in pandas DataFrame after grouping and with additional conditions  </p>

<pre><code>df = pd.DataFrame({ 
    'A'  :[4,5,7,8,2,3,5,2,1,1,4,4,2,4,5,1,3,9,7,9], 
    'B'  :[9,5,7,8,3,3,5,2,1,1,4,4,2,4,5,1,3,5,7,9], 
    'C' :[9,5,7,8,3,3,5,2,1,1,4,4,2,4,5,1,3,5,7,9], 
    'D' :[1,0,1,0,1,1,0,0,1,1,0,0,0,1,1,1,0,0,1,0] 
})
df1 = df.groupby(['A', 'B'], as_index=False).transform('sum')
df1 = df.join(df.groupby(['A'])['C'].sum(), on='A', rsuffix='_inward')

df1
</code></pre>

<p>In above query it is able to sum and give output but how do I add condition for <code>df['D'] == 1</code></p>

<p>Expected output </p>

<pre><code>    A  B  C  D  C_inward
0   4  9  9  1        13
2   7  7  7  1        14
4   2  3  3  1         3
5   3  3  3  1         3
8   1  1  1  1         3
9   1  1  1  1         3
13  4  4  4  1        13
14  5  5  5  1        5
15  1  1  1  1         3
18  7  7  7  1        14
</code></pre>

<p>You can add <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p>

<pre><code>mask = df['D'] == 1
df1 = df[mask].join(df[mask].groupby(['A'])['C'].sum(), on='A', rsuffix='_inward')

print (df1)
    A  B  C  D  C_inward
0   4  9  9  1        13
2   7  7  7  1        14
4   2  3  3  1         3
5   3  3  3  1         3
8   1  1  1  1         3
9   1  1  1  1         3
13  4  4  4  1        13
14  5  5  5  1         5
15  1  1  1  1         3
18  7  7  7  1        14
</code></pre>

python pandas dataframe