0

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.

5
  • why is the logic behind the z characters? Commented Aug 9, 2022 at 17:17
  • x, y and z are just dummy variables Commented Aug 9, 2022 at 17:23
  • so would you supply a list of values in Col1 that you would like to change in Col2? Commented Aug 9, 2022 at 17:25
  • No, Col1 is the column that I want to explode. A, B and C are also dummy variables. Commented Aug 9, 2022 at 17:26
  • If you use df.explode('Col1') then Col1 will have A,B,C, Col2 will have all x's and Col3 will have all y's. What is the logic for the z's to come in? Commented Aug 9, 2022 at 17:28

1 Answer 1

0

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks it works great. Nice use of apply/assign!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.