我有一个数据框,其中包含描述建筑物屋顶表面的记录,因此每个建筑物都有多个平面,其中包含一个区域和一个形状的描述.例如
df=pd.DataFrame([[1000, 12, 'slope'],
[1000, 10, 'flat'],
[1001, 10, 'slope'],
[1001, 15, 'flat'],
[1001, 7, 'slope']],
index = [1,2,3,4,5],
columns=['building_id', 'area', 'form'],
)
df
building_id area form
1 1000 12 slope
2 1000 10 flat
3 1001 10 slope
4 1001 15 flat
5 1001 7 slope
我希望将这些行组合在一起,因此每个建筑物都有一个,总屋顶面积和主要屋顶形式 – 即具有该建筑物最大面积的形式,而不是最常出现的形式:
df_out
building_id area form
1 1000 22 slope
2 1001 32 slope
我需要这样的东西:
group_functions={'area' : ['sum'],
'form' : lambda x: find_predominant(x)}
df_out = df.groupby('building_id').agg(group_functions)
但是find_predominant需要是area和form的函数:它返回字符串’flat’或’slope’,具体取决于具有该building_id的最大区域.
find_predominant的功能是什么?或者哪个脚本会产生相同的效果?
解决方法:
您可以使用sort_values并在agg之后分配值
(df.groupby(['building_id','form'])['area']
.sum()
.sort_values()
.reset_index(level=1)
.groupby(level=0)
.agg({'form':'last','area':'sum'}))
form area
building_id
1000 slope 22
1001 slope 32
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。