Home > Mobile >  Pandas assign error - keyword can't be an expression
Pandas assign error - keyword can't be an expression

Time:10-16

I can assign new columns to a DataFrame as follows:

df_so = pd.DataFrame.from_dict({0: 'jane',
 1: 'baz',
 2: 'baz',
 3: 'dave',
 4: 'dave',
 5: 'dave'},orient='index',columns=["name"])


df_so.assign(val="bar")
index name val
0 jane bar
1 baz bar
2 baz bar
3 dave bar
4 dave bar
5 dave bar

Issue

If I try assign with an f string I get the following error

an_other = "another"
df_so.assign(f"{an_other}_val"="bar")

SyntaxError: keyword can't be an expression

Is there any workaround while still using assign?

CodePudding user response:

yes, with dictionary unpacking:

>>> an_other = "another"
>>> df_so.assign(**{f"{an_other}_val": "bar"})

   name another_val
0  jane         bar
1   baz         bar
2   baz         bar
3  dave         bar
4  dave         bar
5  dave         bar

Key-value pairs of the dictionary will be passed to .assign; the contents of the dictionary will have been already established at that point.

  • Related