I have a Dataframe like this
data = [[1, [10, 11]], [1, [15, 16]], [2, [20, 24]], [2, [22, 23]]]
df = pd.DataFrame(data, columns = ['id', 'val'])
id val
0 1 [10, 11]
1 2 [15, 16]
Here length of each list in val
is same.
I want to explode val
row wise. I could not fine a direct way of doing it .
So as work around I used
df.explode('val')
Now I want to use df.pivot
but before that I want to add column names for each id
.
Something like this
id val col_name
0 1 10 col_1
0 1 11 col_2
1 2 15 col_1
1 2 16 col_2
How can I add col_name
using groupby
??
This will help me pivot the dataframe.
Also is there any direct way of explode row wise which looks like
id col_1 col_2
1 10 11
2 15 16