以新的列名作为字符串进行分配

以新的列名作为字符串进行分配

本文介绍了大 pandas 以新的列名作为字符串进行分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近发现了熊猫"assign"方法

I recently discovered pandas "assign" method 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.

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

但是如果我想命名新列"ln(A)"怎么办?例如.

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

df.assign(ln(A) = lambda x: np.log(x.A))
df.assign("ln(A)" = lambda x: np.log(x.A))


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

我知道我可以在.assign调用之后立即重命名该列,但是我想了解更多有关此方法及其语法的信息.

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

推荐答案

您可以将关键字参数作为字典传递给assign,如下所示:

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

这篇关于大 pandas 以新的列名作为字符串进行分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!