3 回答

TA贡献1772条经验 获得超6个赞
为月份和年份分配一列,并使用pivot:
df.assign(month=df.date.dt.month,year=df.date.dt.year).pivot('year','month','ppt')
在您的情况下,这给出:
month 1 2 3 4 5 11 12
year
2016 NaN NaN NaN NaN NaN 253.379993 52.709998
2017 9.03 10.05 16.56 45.509998 103.829997 NaN NaN

TA贡献1841条经验 获得超3个赞
使用pivot_table:
df.pivot_table(index=df.date.dt.year, columns=df.date.dt.month, values='ppt')
date 1 2 3 4 5 11 12
date
2016 NaN NaN NaN NaN NaN 253.379993 52.709998
2017 9.03 10.05 16.56 45.509998 103.829997 NaN NaN

TA贡献1807条经验 获得超9个赞
在无法执行上述建议后,我设法找到了解决方法。虽然它涉及更多步骤,但无法找出问题所在的挫败感远远超过了额外代码行的努力......
df['M'] = df.index.month #extracting month and years and creating new columns
df['Y'] = df.index.year
df_pivot = df.pivot_table(index=df.Y, columns=df.M, values='ppt') #pivot with these columns, rather than the index
不过还是谢谢大家的建议:)
添加回答
举报