0

Following the Pandas explode() method documentation, one can explode a list in a row into multiple rows:

df = pd.DataFrame({'A': [[1, 2, 3], 'foo', None, [3, 4]], 'B': 1})
df.explode('A')

However, the DataFrame() I get from a database contains lists that are seen as strings :

df = pd.DataFrame({'A': ["[1, 2, 3]", 'foo', None, "[3, 4]"], 'B': 1})
df.explode('A')
# Does not fail, but does not explode "[1, 2, 3]"

Outside Pandas, I use ast.literal_eval() but don't know how to make it work for my column.

How to cast my 'A' column as list so that explode('A') works ?

1 Answer 1

2

You could try with DataFrame.apply:

def f(x):
    try:
        return ast.literal_eval(x)
    except Exception:
        return x


df['A']=df['A'].apply(f)
df.explode('A')

      A  B
0     1  1
0     2  1
0     3  1
1   foo  1
2  None  1
3     3  1
3     4  1
Sign up to request clarification or add additional context in comments.

3 Comments

use same with literal eval, its safer than eval
if this does exactly the same thing really

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.