gpt4 book ai didi

python - 按 pandas 数据框中的列中的重复值进行聚合

转载 作者:太空宇宙 更新时间:2023-11-03 17:46:35 25 4
gpt4 key购买 nike

我有一个数据框如下:

             value     identifier
2007-01-01 0.781611 55
2007-01-01 0.766152 56
2007-01-01 0.766152 57
2007-02-01 0.705615 55
2007-02-01 0.032134 56
2007-02-01 0.032134 57
2008-01-01 0.026512 55
2008-01-01 0.993124 56
2008-01-01 0.993124 57
2008-02-01 0.226420 55
2008-02-01 0.033860 56
2008-02-01 0.033860 57

如何按标识符列中的值进行聚合,如下所示:

           value  
2007-01-01 0.766 # (average of identifiers 55, 56 and 57 for this date)
2007-02-01 0.25
2008-01-01 etc...
2008-02-01

最佳答案

如果您的索引是日期时间,那么您可以访问 .date 属性,如果不是,您可以使用 df.index = pd.to_datetime(df.index) 进行转换 然后对日期执行 groupby 并计算平均值:

In [214]:

df.groupby(df.index.date)['value'].mean()
Out[214]:
2007-01-01 0.771305
2007-02-01 0.256628
2008-01-01 0.670920
2008-02-01 0.098047
Name: value, dtype: float64

关于python - 按 pandas 数据框中的列中的重复值进行聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29701242/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com