2

I need to convert a pandas dataframe with multiple rows into one row

     col1.    col2.    col3.    col4.    col5.
0    1234     rule_1.  ''       ''       ''
1    1234     ''       rule_2.  ''       ''
2    2356     rule_1.  ''       ''       ''
3    7890     ''       ''       rule_3   ''
4    1234     ''       ''       ''       rule_4

I need to groupby by col1. and fill in the empty fields with the fields from the other rows.

     col1.    col2.    col3.    col4.    col5
0    1234     rule_1.  rule_2   ''       rule_4
1    2356     rule_1.  ''       ''       ''
3    7890     ''       ''       rule_3   ''

1 Answer 1

2

IIUC first mask the '' to nan , then we do groupby + first

s=df.mask(df=="''").groupby('col1.').first()
s # you can add reset_index()
         col2.    col3.   col4.   col5.
col1.                                  
1234   rule_1.  rule_2.     NaN  rule_4
2356   rule_1.      NaN     NaN     NaN
7890       NaN      NaN  rule_3     NaN
Sign up to request clarification or add additional context in comments.

1 Comment

That is a slick solution!

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.