由两列组成的组取最高和(Pandas)



查看哪个客户在2月份的价格总额最高。2022年2月1日

数据

client  box Price   date
charles AA  5,000   2/1/2022
charles AA  5,050   2/1/2022
charles AA  5,075   2/1/2022
cara    BB  25,116  2/1/2022
cara    BB  5,154   2/1/2022
lu      CC  0       2/1/2022
max     DD  10,000  3/1/2022

所需

client   box Price   date
cara     BB  30,270  2/1/2022

执行

df.groupby(['client','date']) 
.agg({'Price':'sum'}).reset_index() 

任何建议都是有益的。

idxmax将返回最大值的索引,然后您可以使用该索引查找所需的行。请注意,在两个客户并列最高价格的情况下,它将只返回第一次出现的情况。

示例:

(
df
# Fist filter to only Februrary
.loc[lambda df_: df_["date"].dt.month == 2]
.groupby(["client", "box"])["Price"]
.sum()
.reset_index()
# Then select where price is max
.loc[lambda df_: df_["Price"].idxmax()]
)
import pandas as pd
df = pd.DataFrame({"client": ["charles", "charles", "charles", "cara", "cara", "lu", "max"],
"box": ["AA", "AA", "AA", "BB", "BB", "CC", "DD"],
"price": [5000, 5050, 5075, 25116, 5154, 0, 10000],
"date": ["2/1/2022", "2/1/2022", "2/1/2022", "2/1/2022", "2/1/2022", "2/1/2022", "3/1/2022"]})
# print(df)
print(df.groupby(by= ["client", "box", "date"]).price.aggregate('sum'))

基于OP所需的输出,这里有一个建议:

gdf = df.groupby(['client','box','date']).agg({'Price':'sum'}).reset_index()
gdf.loc[gdf.Price.idxmax()]

如果每个客户端的框总是相同的。

df = df.groupby(["client", "date"]).agg({"box": "first", "Price": "sum"})
df = df[df["Price"].eq(df["Price"].max())].reset_index()

每个客户端的If框可能不同。

df = df.groupby(["client", "date", "box"]).agg({"Price": "sum"})
df = df[df["Price"].eq(df["Price"].max())].reset_index()

最新更新