如何在pandas中将方括号用作变量名称的一部分?

huangapple go评论62阅读模式
英文:

How to use square brackets as part of a variable name in pandas?

问题

我正在尝试使用pandas.assign函数。该函数将另一列添加到现有列中。

例如:

DataFrame1 = DataFrame1.assign(NewColName=[1,2,3,4])

会添加一个名为"NewColName"的新列。然而,我的理想列名应该是"Weight [kg]",当我尝试使用"[ ]"时,函数停止工作。我尝试过在"[ ]"周围应用%'s\'s和其他类似的方法,但都没有成功。

我知道我可以在给定任何名称后重命名列,例如"PlaceHolderName",但是否有一行代码的方法来做到这一点?该函数不接受列名在" "内,所以它与像Index="[[asdsa][[" ....这样的东西不同,我可以在" "内输入任何我想要的内容。

谢谢。

英文:

I am trying to use pandas.assign function. The function adds another column into an existing column.

For example

DataFrame1 = DataFrame1.assign(NewColName=[1,2,3,4])

Adds a new column named "NewColName". However, my ideal column name would be "Weight [kg]", and when I try to use "[ ]" the function ceases to work. I have tried applying %'s \'s and other similar methods around the "[ ]" with no success.

I know I can just rename the column after giving it any name, such as &quot;PlaceHolderName&quot;, but is there a way to do this with one line of code? That function does not accept column name inside<br> &quot; &quot;, so it feels different compared to something like Index=&quot;[[asdsa][[&quot; .... where I can type whatever I want inside the &quot; &quot;.

Thank you.

答案1

得分: 2

使用字典拆包将名称作为参数传递:

DataFrame1.assign(**{'Weight [kg]': [1,2,3,4]})
英文:

Use dictionary unpacking to pass the name as parameter:

DataFrame1.assign(**{&#39;Weight [kg]&#39;: [1,2,3,4]})

huangapple
  • 本文由 发表于 2023年7月17日 13:34:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76701715.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定