How do I collapse a dataframe?

Viewed 36

I have a dataframe where some of the values are NA. I want to remove the NAs and replace them with data, where data is available.

This is what the dataframe looks like -

<dataframe: flowers>
type       pedals    depth    height
iris       4         NA        NA
iris       NA        3         NA
iris       NA        NA        8
sunflow    NA        5        NA
sunflow    NA        NA       13
sunflow    12        NA       NA
poppie     1         NA       NA
poppie     NA        2        NA

This is what I'm trying to do-

<dataframe: flowers>
type       pedals    depth    height
iris       4         3        8
sunflow    12        5        13
poppie     1         2        NA
1 Answers

First, you would need to replace the NaN with zeros, and then you can just group by and sum.

df = df.fillna(0)
final_df = df.groupby('type').sum()

Since the NaN values are zeros, the sum will simply take the only non-zero value for all rows of a given type.

Related