1

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.

Niko Föhr
  • 28,336
  • 10
  • 93
  • 96

1 Answers1

2

Use dictionary unpacking to pass the name as parameter:

DataFrame1.assign(**{'Weight [kg]': [1,2,3,4]})
mozway
  • 194,879
  • 13
  • 39
  • 75