gpt4 book ai didi

python - 按月 reshape Pandas 数据框

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

任务是改造下表

import pandas as pd
import numpy as np

index = pd.date_range('2000-1-1', periods=700, freq='D')
df = pd.DataFrame(np.random.randn(700), index=index, columns=["values"])

df.groupby(by=[df.index.year, df.index.month]).sum()

In[1]: df

Out[1]:
values
2000 1 1.181000
2 -8.005783
3 6.590623
4 -6.266232
5 1.266315
6 0.384050
7 -1.418357
8 -3.132253
9 0.005496
10 -6.646101
11 9.616482
12 3.960872
2001 1 -0.989869
2 -2.845278
3 -1.518746
4 2.984735
5 -2.616795
6 8.360319
7 5.659576
8 0.279863
9 -5.220678
10 5.077400
11 1.332519

看起来像这样

      Jan  Feb  Mar  Apr  May  Jun  Jul  Aug  Sep  Oct  Nov  Dec  
2000 1.2 -8.0 6.6 -6.3 1.2 0.4 -1.4 -3.1 0.0 -6.6 9.6 3.9
2001 -0.9 -2.8 -1.5 3.0 -2.6 8.3 5.7 0.3 -5.2 5.1 1.3

此外,我需要添加一个额外的列来汇总每年的值

      Jan  Feb  Mar  Apr  May  Jun  Jul  Aug  Sep  Oct  Nov  Dec  Year
2000 1.2 -8.0 6.6 -6.3 1.2 0.4 -1.4 -3.1 0.0 -6.6 9.6 3.9 4.7
2001 -0.9 -2.8 -1.5 3.0 -2.6 8.3 5.7 0.3 -5.2 5.1 1.3 10.7

有没有一种快速的 pandas pivotal 方法可以解决这个问题?

最佳答案

在你的 groupby 中使用 strftime('%b')

df['values'].groupby([df.index.year, df.index.strftime('%b')]).sum().unstack()

enter image description here


保持月份顺序

df['values'].groupby([df.index.year, df.index.strftime('%b')], sort=False).sum().unstack()

enter image description here


'Year'结尾

df['values'].groupby([df.index.year, df.index.strftime('%b')], sort=False).sum() \
.unstack().assign(Year=df.groupby(df.index.year).sum())

enter image description here

关于python - 按月 reshape Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41340950/

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