3

I have dataframe like below

enter image description here

A,B,C,D
91102,1,john,
91102,2,john,
91102,3,john,
91102,1,,mary
91102,2,,mary
91102,3,,mary
91103,1,sarah,
91103,2,sarah,
91103,3,sarah,
91103,1,,khan
91103,2,,khan
91103,3,,khan

and I want groupby column A and column B and want get desired output like below enter image description here

A,B,C,D
91102,1,john,mary
91102,2,john,mary
91102,3,john,mary
91103,1,sarah,khan
91103,2,sarah,khan
91103,3,sarah,khan

I tried below but not giving desired output

df=df.groupby(['A', 'B'], as_index=False).agg('' .join)
3
  • 1
    Can you please do df.to_dict() and post the result here to give us an easier time reconstructing your dataframe? Commented Sep 21, 2022 at 23:42
  • Can you please edit your question and put the sample input and expected output as text? (Not as a picture?) Commented Sep 21, 2022 at 23:42
  • I added text format.. thanks Commented Sep 22, 2022 at 0:06

2 Answers 2

2

In the groupby you could back-fill and then take the first row of the group.

df.groupby(['A','B'], as_index=False).apply(lambda x: x.bfill().iloc[0])

Result

       A  B      C     D
0  91102  1   john  mary
1  91102  2   john  mary
2  91102  3   john  mary
3  91103  1  sarah  khan
4  91103  2  sarah  khan
5  91103  3  sarah  khan
Sign up to request clarification or add additional context in comments.

Comments

1

Try:

x = df.set_index(["A", "B"]).stack().unstack().reset_index()
print(x)

Prints:

       A  B      C     D
0  91102  1   john  mary
1  91102  2   john  mary
2  91102  3   john  mary
3  91103  1  sarah  khan
4  91103  2  sarah  khan
5  91103  3  sarah  khan

Comments

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.