[英]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.