Reshape dataframe of list to another dataframe

Viewed 129

I have a dataframe of names and lists like this:

| Name | value |
|:-----|------:|
| A    |[1,4,7]|
| A    |[9,2,5]|
| A    |[6,9,3]|
| A    |[1,4,7]|
| A    |[9,2,5]|
| B    |[6,9,3]|
| B    |[1,4,7]|
| B    |[9,2,5]|
| B    |[6,9,3]|
| B    |[1,4,7]|

I want to reshape this dataframe to another dataframe as for all name there will have 3 lists like this:

| Name |   value   |
|:-----|----------:|
| A    |[1,9,6,1,9]|
| A    |[4,2,9,4,2]|
| A    |[7,5,3,7,5]|
| B    |[6,1,9,6,1]|
| B    |[9,4,2,9,4]|
| B    |[3,7,5,3,7]|

Is there any kind of simpler way to do this by using pandas?

2 Answers

Using groupby+pd.Series+melt

df2 = df.groupby('Name').apply(lambda s: pd.Series([s['value'].str[k].agg(list) for k 
in range(3)])).T.melt()

The dataframe looks like this:

   Name         value
0   A       [1, 9, 6, 1, 9]
1   A       [4, 2, 9, 4, 2]
2   A       [7, 5, 3, 7, 5]
3   B       [6, 1, 9, 6, 1]
4   B       [9, 4, 2, 9, 4]
5   B       [3, 7, 5, 3, 7]

You can, but a much better idea is to split your lists into separate series:

res = pd.concat((pd.DataFrame(np.array(grp['value'].tolist()).T.reshape(3, -1))\
                 .assign(Name=key) for key, grp in df.groupby('Name')),
                ignore_index=True)

print(res)

   0  1  2  3  4 Name
0  1  9  6  1  9    A
1  4  2  9  4  2    A
2  7  5  3  7  5    A
3  6  1  9  6  1    B
4  9  4  2  9  4    B
5  3  7  5  3  7    B
Related