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 concatenate columns using pd.eval

Is it possible to concatenate columns together like in the example below using pd.eval? I keep getting TypeError: unsupported operand type(s) for +: 'object' and '<class 'str'>'.

import pandas as pd

df = pd.DataFrame([{'a': 1, 'b': 'x'}, {'a': 2, 'b': 'y'}])

df['a'].astype('str') + '_' + df['b']
# 0    1_x
# 1    2_y
# dtype: object

pd.eval("df['a'].astype('str') + '_' + df['b']")
# TypeError: unsupported operand type(s) for +: 'object' and '<class 'str'>'

>Solution :

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

eval supports Series and DataFrame objects, so you could use the following workaround:

pd.eval("df.a.astype('str') + df.assign(underline='_').underline + df.b")

Result:

0    1_x
1    2_y
dtype: object

(I’m not saying this is a reasonable approach, just trying to answer this particular question)

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