Pandas – explode a column and set a specific value to a column for replicated rows

Question:

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.

Asked By: Mathieu

||

Answers:

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
Answered By: Ynjxsjmh
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.