pandas assign with new column name as string pandas assign with new column name as string python python

pandas assign with new column name as string


You can pass the keyword arguments to assign as a dictionary, like so:

kwargs = {"ln(A)" : lambda x: np.log(x.A)}df.assign(**kwargs)    A         B     ln(A)0   1  0.500033  0.0000001   2 -0.392229  0.6931472   3  0.385512  1.0986123   4 -0.029816  1.3862944   5 -2.386748  1.6094385   6 -1.828487  1.7917596   7  0.096117  1.9459107   8 -2.867469  2.0794428   9 -0.731787  2.1972259  10 -0.686110  2.302585


assign 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 link

use insert instead for inplace transformation

df.insert(2, 'ln(A)', np.log(df.A))df

enter image description here


use concat if you don't want inplace

pd.concat([df, np.log(df.A).rename('log(A)')], axis=1)

enter image description here