pandas assign with new column name as string

青春壹個敷衍的年華 提交于 2019-11-30 04:18:47

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.000000
1   2 -0.392229  0.693147
2   3  0.385512  1.098612
3   4 -0.029816  1.386294
4   5 -2.386748  1.609438
5   6 -1.828487  1.791759
6   7  0.096117  1.945910
7   8 -2.867469  2.079442
8   9 -0.731787  2.197225
9  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


use concat if you don't want inplace

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!