Issue
i have a dataframe like this"
A B C
0 [X] [1] [aa, bb, cc]
1 [Y] [2] [xx, yy]
i want to change it to:
A B C
0 X 1 aa
1 X 1 bb
2 X 1 cc
3 Y 2 xx
4 Y 2 yy
Solution
You can use explode method chained like this,
df.explode('A').explode('B').explode('C').reset_index(drop=True)
A B C
0 X 1 aa
1 X 1 bb
2 X 1 cc
3 Y 2 xx
4 Y 2 yy
Alternatively, you can apply pd.Series.explode
on the dataframe like this,
df.apply(pd.Series.explode).reset_index(drop=True)
In pandas 1.3+ you can use a list of columns to explode on,
So the code will look like,
df.explode(['A', 'B', 'C']).reset_index(drop=True)
Answered By - Sreeram TP
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.