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

Question:

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.

Asked By: Jugilismaani

||

Answers:

Use dictionary unpacking to pass the name as parameter:

DataFrame1.assign(**{'Weight [kg]': [1,2,3,4]})
Answered By: mozway
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.