查找依赖于熊猫中列的最小值

时间:2020-06-13 14:33:37

标签: python pandas

我的数据看起来像这样


data = [['29/10/18', 'EDF', 'Online', 400, 500, 300], 
        ['29/10/18', 'EDF', 'Standard', 200, 100, 300], 
        ['29/10/18', 'NPower', 'Saver', 600, 500, 700],
        ['30/10/18', 'British Gas', 'Fixed Tariff', 300, 500, 600]] 


df = pd.DataFrame(data, columns = ['date', 'Supplier', 'Product', 'Eastern Price', 'Southern Price', 'South West Price']) 

print(df)

我正在寻找按地区每天最便宜的价格。

所以输出应该看起来像

Date Region MinPrice

有人可以帮忙吗?

到目前为止,这是我所拥有的,但是我想在每个区域(在我的数据集中大约有15个)使用它,只是按日期而不是在数据集中的每个条目进行设置

df.groupby(['date'])['date','Eastern Price'].transform('min')

2 个答案:

答案 0 :(得分:2)

IIUC需要先melt,然后再groupby才能轻松找到我们可以使用filter的所有区域列

df1 = pd.melt(
    df,
    id_vars=["date"],
    value_vars=df.filter(like="Price"), # this finds the region columns.
    var_name="region",
    value_name="amount",
).groupby(["date", "region"]).agg(minPrice=('amount','min'))

print(df1)

                             minPrice
date       region                    
2018-10-29 Eastern Price          200
           South West Price       300
           Southern Price         100
2018-10-30 Eastern Price          300
           South West Price       600
           Southern Price         500

答案 1 :(得分:2)

我们可以用stackmin

df.set_index(['date', 'Supplier', 'Product']).stack().min(level=[0,3])
date                      
29/10/18  Eastern Price       200
          Southern Price      100
          South West Price    300
30/10/18  Eastern Price       300
          Southern Price      500
          South West Price    600
dtype: int64