[Pandas]The way to assign a new column based on if statement
<p>I know assign could help to create/change one column based on lambda function like this: </p>

<pre><code>df.assign(c = lambda x: x.sum())
</code></pre>

<p>But I couldn't find a way to do this with if-statement if I want to make the statement inline instead of doing it separately outside of the operation. </p>

<p>Is it possible to realize this without doing anything else outside of the operation:</p>

<pre><code>df.assign(c = lambda x: x.num_col.sum() if x.num_col &gt; 0)
</code></pre>

<p>The above command returns "<strong>SyntaxError</strong>: invalid syntax"</p>

<p>IIUC you can do it this way:</p>

<p><strong>Data:</strong></p>

<pre><code>In [6]: df = pd.DataFrame(np.random.randn(10,2),columns=list('ab'))

In [7]: df
Out[7]:
          a         b
0  0.493970  1.095644
1  0.128510 -0.542144
2  0.136247 -0.544499
3 -0.540835 -0.100574
4  0.052725 -0.164856
5 -1.201619  1.578153
6  1.921872  0.505875
7 -2.519725  0.282050
8 -1.581868 -0.240352
9 -0.071207 -1.366953

In [8]: df.ix[:6]
Out[8]:
          a         b
0  0.493970  1.095644
1  0.128510 -0.542144
2  0.136247 -0.544499
3 -0.540835 -0.100574
4  0.052725 -0.164856
5 -1.201619  1.578153
6  1.921872  0.505875
</code></pre>

<p>let's find a sum of positive values in <code>a</code> column for the indexes: <code>[0:6]</code>:</p>

<pre><code>In [9]: df.ix[:6].query('a &gt; 0').a.sum()
Out[9]: 2.733322288547374
</code></pre>

<p><strong>Solution:</strong></p>

<pre><code>In [10]: df.ix[:6].assign(c=lambda x: x.query('a &gt; 0').a.sum())
Out[10]:
          a         b         c
0  0.493970  1.095644  2.733322
1  0.128510 -0.542144  2.733322
2  0.136247 -0.544499  2.733322
3 -0.540835 -0.100574  2.733322
4  0.052725 -0.164856  2.733322
5 -1.201619  1.578153  2.733322
6  1.921872  0.505875  2.733322
</code></pre>

<p>the same with renamed columns:</p>

<pre><code>In [11]: df.ix[:6].rename(columns={'a':'AAA', 'b':'BBB'}).assign(c=lambda x: x.query('AAA &gt; 0').AAA.sum())
Out[11]:
        AAA       BBB         c
0  0.493970  1.095644  2.733322
1  0.128510 -0.542144  2.733322
2  0.136247 -0.544499  2.733322
3 -0.540835 -0.100574  2.733322
4  0.052725 -0.164856  2.733322
5 -1.201619  1.578153  2.733322
6  1.921872  0.505875  2.733322
</code></pre>

python pandas dataframe