How can I expand columns containing multiple elements?

I have a DataFrame where one of the columns is a string representation set. Is it possible to "expand" any lines like this?

Example:

     ColA                 ColB                    ColC   ColD
0    "one item in a set"  "{'item 1'}"            "..."  "..."
1    "several in a set"   "{'item 1', 'item 2'}"  "..."  "..."
...

It should become:

     ColA                 ColB       ColC   ColD 
0    "one item in a set"  'item 1'   "..."  "..."
1    "several in a set"   'item 1'   "..."  "..." 
2    "several in a set"   'item 2'   "..."  "..."
... 
+4
source share
1 answer

You can:

df2 = df.colB.str[1:-1].str.split(',', expand=True)
df2 = df2.stack().reset_index()
df2 = df2.drop('level_1', axis=1).rename(columns={0: 'colB'}).set_index('level_0')
df = df.drop('colB', axis=1)
df = pd.concat([df, df2], axis=1)

After removal {}, .split()on ',' expandin the new columns and .stack(), then clean.

+1
source

Source: https://habr.com/ru/post/1618426/


All Articles