如何使用 groupby 和 min 创建一个新的数据框

How to create a new dataframe with groupby and min

我有一个包含以下字段的 Pandas DataFrame:

week
zipcode
cost

我想通过执行以下 SQL:

从上面的 DataFrame(“week”、“zipcode”和“min_cost”)创建一个新的 DataFrame
SELECT week, zipcode, MIN(cost) min_cost
FROM the_first_dataframe
GROUP BY 1, 2

我的局限是我不能使用 pandasql,希望仅通过纯 pandas 操作来实现。

任何见解将不胜感激。

尝试 groupby + 命名聚合:

out = the_first_dataframe.groupby(['week','zipcode'], as_index=False).agg(min_cost=('cost','min'))

多种方式实现

选项1 :使用groupby agg并添加到框架

 the_first_dataframe.groupby(['week','zipcode'])['cost'].agg('min').to_frame('min_cost')

选项2:groupy,成本将结转。重命名

the_first_dataframe.groupby(['week','zipcode']).min().rename(columns={'cost':'min_cost'})