Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas assign error – keyword can't be an expression

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading