[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>The syntax is invalid because you're using the ternary condition, but only the first half.</p>

<p>The ternary condition allows you to write an <code>if</code> statement like this:</p>

<pre><code>a = 1 if b &gt; 0 else 0
</code></pre>

<p>In your case, you could write something like:</p>

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

<p>Note the addition of the <code>else 0</code> at the end.</p>

python pandas dataframe