Search code examples
pythonpandaseval

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

  • 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)