我有一个数据框架框架:
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
我希望上面的数据框按城市分组并产生以下结果:
x y z city
-0.459476 20.439870 1.142743 hyd
N/A 9.827238 -99.950162 pune
我使用以下代码:
newdf = frame[frame.columns[:3]]
newdf1 = list(newdf.columns.values)
df1 = frame.groupby(city)[newdf1].sum().reset_index()
结果没有给出列x和N / A.
如何解决此问题?
答案 0 :(得分:2)
groupby
ffill
bfill
,然后 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