首页 > 解决方案 > 基于另一个数据框创建一个新的 Min() 和 Max() 列

问题描述

我正在尝试根据现有数据框中的 Min 和 Min 在新数据框中创建两列。当使用 groupby 时,它给出最小和最大 NAN 值

df.groupby('street').min()['sold_price']
df.groupby('street').max()['sold_price']

来自现有数据框的样本。

street_name sold_price
A            100,000
A            200,100
B            50,000
B            100,000

新的数据框应该是

street_name   min        max
A             100,000    200,000
B             50,000     100,000

标签: pythonpandas

解决方案


它应该是

(df.groupby("street_name", as_index=False)
    ["sold_price"].agg(["min","max"])
)

更新:重命名:

(df.groupby("street_name", as_index=False)
    ["sold_price"].agg({'low':'min', 'high':'max'})
)

推荐阅读