Home > Enterprise >  Trying to convert a string into a list in Pandas
Trying to convert a string into a list in Pandas

Time:05-30

I am trying to convert a column, which looks something like this

cleaned
['11-111']
['12-345', '67-789']
['00-000', '01-234']

into a list, since I read that Pandas initially interprets list as strings from this article: https://towardsdatascience.com/dealing-with-list-values-in-pandas-dataframes-a177e534f173

I using the function mentioned in the article

master["cleaned"] = master["cleaned"].apply(eval)

but I am getting this error

eval() arg 1 must be a string, bytes or code object

I tried looking them up, but I can't figure it out

CodePudding user response:

df.cleaned = pd.eval(df.cleaned)

There doesn't appear to be a built it to deal with failures, so you can make it yourself:

def try_eval(x):
    try:
        return eval(x)
    except:
        return x

df.cleaned = df.cleaned.apply(try_eval)

Then you can look for the ones that didn't convert by doing:

df.cleaned[df.cleaned.apply(lambda x: isinstance(x, str))]
  • Related