英文:
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 "PlaceHolderName"
, but is there a way to do this with one line of code? That function does not accept column name inside<br> " "
, so it feels different compared to something like Index="[[asdsa][[" ....
where I can type whatever I want inside the " "
.
Thank you.
答案1
得分: 2
使用字典拆包将名称作为参数传递:
DataFrame1.assign(**{'Weight [kg]': [1,2,3,4]})
英文:
Use dictionary unpacking to pass the name as parameter:
DataFrame1.assign(**{'Weight [kg]': [1,2,3,4]})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论