pandas assign with new column name as string
<p>I recently discovered pandas <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html" rel="nofollow">"assign" method</a> which I find very elegant.
My issue is that the name of the new column is assigned as keyword, so it cannot have spaces or dashes in it. </p>

<pre><code>df = DataFrame({'A': range(1, 11), 'B': np.random.randn(10)})
df.assign(ln_A = lambda x: np.log(x.A))
        A         B      ln_A
0   1  0.426905  0.000000
1   2 -0.780949  0.693147
2   3 -0.418711  1.098612
3   4 -0.269708  1.386294
4   5 -0.274002  1.609438
5   6 -0.500792  1.791759
6   7  1.649697  1.945910
7   8 -1.495604  2.079442
8   9  0.549296  2.197225
9  10 -0.758542  2.302585
</code></pre>

<p>but what if I want to name the new column "ln(A)" for example?
E.g. </p>

<pre><code>df.assign(ln(A) = lambda x: np.log(x.A))
df.assign("ln(A)" = lambda x: np.log(x.A))


File "&lt;ipython-input-7-de0da86dce68&gt;", line 1
df.assign(ln(A) = lambda x: np.log(x.A))
SyntaxError: keyword can't be an expression
</code></pre>

<p>I know I could rename the column right after the .assign call, but I want to understand more about this method and its syntax.</p>

<p><code>assign</code> expects a bunch of key word arguments.  It will, in turn, assign columns with the names of the key words.  That's handy, but you can't pass an expression as the key word.  This is spelled out by @EdChum in the comments with this <a href="https://docs.python.org/3.2/reference/lexical_analysis.html#identifiers" rel="nofollow">link</a></p>

<p>use <code>insert</code> instead for inplace transformation</p>

<pre><code>df.insert(2, 'ln(A)', np.log(df.A))
df
</code></pre>

<p><a href="http://i.stack.imgur.com/TUyep.png" rel="nofollow"><img src="http://i.stack.imgur.com/TUyep.png" alt="enter image description here"></a></p>

<hr>

<p>use <code>concat</code> if you don't want inplace</p>

<pre><code>pd.concat([df, np.log(df.A).rename('log(A)')], axis=1)
</code></pre>

<p><a href="http://i.stack.imgur.com/TUyep.png" rel="nofollow"><img src="http://i.stack.imgur.com/TUyep.png" alt="enter image description here"></a></p>

python pandas assign columnname