【问题标题】:Get values on a big DataFrame Python [duplicate]在大 DataFrame Python 上获取值 [重复]
【发布时间】:2019-03-30 08:15:16
【问题描述】:

我有一个大数据框,其结构如下:

ID  Year Consumption
1   2012      24
2   2012      20
3   2012      21
1   2013      22
2   2013      23
3   2013      24
4   2013      25

我想要另一个 DataFrame,其中包含出现的第一年,以及每个 ID 的所有时间的最大消耗,如下所示:

ID   First_Year  Max_Consumption
1       2012          24
2       2012          23
3       2012          24
4       2013          25

有没有办法在不使用循环的情况下提取这些数据?我试过这个:

year = list(set(df.Year))
ids = list(set(df.ID))

antiq = list()
max_con = list()

for i in ids:
    df_id = df[df['ID'] == i]
    antiq.append(min(df_id['Year']))
    max_con.append(max(df_id['Consumption']))

但是太慢了。谢谢!

【问题讨论】:

    标签: python pandas pandas-groupby


    【解决方案1】:

    使用GroupBy + agg:

    res = df.groupby('ID', as_index=False).agg({'Year': 'min', 'Consumption': 'max'})
    
    print(res)
    
       ID  Year  Consumption
    0   1  2012           24
    1   2  2012           23
    2   3  2012           24
    3   4  2013           25
    

    【讨论】:

      【解决方案2】:

      groupby 的另一个替代品是pivot_table

      pd.pivot_table(df, index="ID", aggfunc={"Year":min, "Consumption":max})
      

      【讨论】:

        猜你喜欢
        • 2020-05-02
        • 1970-01-01
        • 2017-10-04
        • 1970-01-01
        • 1970-01-01
        • 2018-12-13
        • 1970-01-01
        • 2021-12-26
        • 2017-11-02
        相关资源
        最近更新 更多