Python Dataframe convert each cell-string to a list type and explode

Viewed 62

I have a dataframe consists lists as cells. I run into the issues when I explode it. I understood that the list is stored inside the cell as str type not object type. My code:

xdf = pd.DataFrame({'A':[str([1,2])],'B':[str([10,20])]})

xdf
        A         B
0  [1, 2]  [10, 20]

xdf.apply(pd.Series.explode)

        A         B
0  [1, 2]  [10, 20]

Desired output:

xdf = 
   A   B
0  1  10
0  2  20
2 Answers
xdf.applymap(eval).apply(lambda x: x.explode())

use the below code that

import pandas as pd
xdf = pd.DataFrame({'A':[str([1,2])],'B':[str([10,20])]})
xdf.applymap(lambda x:x.strip("][").split(",")).apply(lambda x:x.explode())

1)by removing symbols and split we convert the STRING LIST to normal list 2)then we explode the list

Related