pythonpandasdataframeassign

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


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
" ", so it feels different compared to something like Index="[[asdsa][[" .... where I can type whatever I want inside the " ".

Thank you.


Solution

  • Use dictionary unpacking to pass the name as parameter:

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