Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

group by in python with columns having N/A values

I have a dataframe frame:

                    x                  y                z    city
        0       -0.459476              NaN              NaN   hyd
        0             NaN        20.439870              NaN   hyd
        0             NaN              NaN         1.142743   hyd
        0             N/A              NaN              NaN   pune
        0             NaN         9.827238              NaN   pune
        0             NaN              NaN       -99.950162   pune

I want the above data frame to group by city and produce the below result:

                x                      y              z    city
            -0.459476              20.439870      1.142743 hyd
               N/A                 9.827238     -99.950162 pune

I am using the below code:

newdf = frame[frame.columns[:3]]
newdf1 = list(newdf.columns.values)
df1 = frame.groupby(city)[newdf1].sum().reset_index()

The result does not give me the column x as it as N/A.

How do I resolve this?

like image 286
Alok Avatar asked Sep 13 '26 20:09

Alok


1 Answers

groupby with ffill bfill then drop_duplicates

df.groupby('city').ffill().bfill().drop_duplicates(keep='first')

          x          y          z  city
0 -0.459476  20.439870   1.142743   hyd
3       N/A   9.827238 -99.950162  pune
like image 134
user3483203 Avatar answered Sep 16 '26 09:09

user3483203



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!