繁体   English   中英

Pandas DataFrame 按两列分组并得到最大值

[英]Pandas DataFrame Groupby two columns and get maximum value

嗨,我在产品和城市两列上使用 groupby,如下图所示,其中包含特定城市中产品的数量订单。 现在,我只想查看每个产品的订单数量最大值的城市。

我的数据截图在这里。

这是我使用的代码:

city_grp = df.groupby(["Product","City"])
p_c_df = pd.DataFrame(city_grp["Quantity Ordered"].sum())

由于您的示例是屏幕截图,因此我必须创建一些自己的数据,但这应该是一个足够好的示例,您可以在自己的数据上进行复制

Since your example is a screenshot I had to create some of my own data, but this should be a good enough example for you to replicate on your own data

#Sample Data
df = pd.DataFrame({
    'Column1' : ['A', 'A', 'A', 'B', 'B', 'B'],
    'Column2' : ['AA', 'AB', 'AB', 'BA', 'BA', 'BB'],
    'Column3' : [100, 200, 100, 300, 200, 100]
})

#Set sample data to a multi-index as in your screenshot
df = df.set_index(['Column1', 'Column2'])

#reset the index to work with the data
df = df.reset_index()

#Group by multiple columns finding only the max of each grouping and reseting the index to the multi-index it was before
df.loc[df.groupby(['Column1'])['Column3'].idxmax()].set_index(['Column1', 'Column2'])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM