I would like to explode a column Col1 of a dataframe and for all the replicated rows, set a specific value z for a given column Col2.
For example if my dataframe df is:
| Col1 | Col2 | Col3 |
|---|---|---|
| [A,B,C] | x | y |
I would like to find a way using df.explode("Col1") and achieve:
| Col1 | Col2 | Col3 |
|---|---|---|
| A | x | y |
| B | z | y |
| C | z | y |
Thank you for any idea.
You can try
out = (df.explode('Col1')
.groupby(level=0)
.apply(lambda g: g.assign(Col2=[g['Col2'].iloc[0]]+['z']*(len(g)-1))) # keep first row of Col2 and replace rest with z
.reset_index(drop=True))
print(out)
Col1 Col2 Col3
0 A x y
1 B z y
2 C z y