Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Collapse rows of a dataframe with common values and fill in blanks

I have a single data frame and every row is duplicated except for two values. In all cases the corresponding duplicate has a blank value in the corresponding row. I want to ‘collapse’ these rows and fill in the blanks.

In the example below, I want to collapse the top DataFrame to mirror the bottom

Example Table

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use groupby + first; first skips over NaN values by default:

collapsed_df = df.groupby("feature_id").first().reset_index()

If the empty spaces are not NaN values, probably will want to fill them with NaN first:

df = df.replace('', np.nan)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading