gpt4 book ai didi

python - 在 python 中将 Series reshape 为 Dataframe 矩阵

转载 作者:太空宇宙 更新时间:2023-11-04 09:50:33 24 4
gpt4 key购买 nike

我有一个包含 305 个条目的系列,这些条目带有数据时间索引。数据看起来像这样

1992-01-31     1.123077 
1992-02-28 -2.174845
1992-03-31 -3.884848
1992-04-30 8.682919
1992-05-29 1.312976
1992-06-30 7.851080
1992-07-31 -3.192788
1992-08-31 -7.351976
1992-09-30 -6.782217
1992-10-30 -17.182738
1992-11-30 3.898782
1992-12-31 -26.190414
1993-01-29 2.233359
1993-02-26 6.709006
continues with monthly data till December 2017

我想将数据 reshape 为一个 DataFrame,其中包含行的所有年份和列的所有月份以及要根据需要填写的数据

        January February  March     etc >>  December
2017 values values values values values
2016 values values values values values
2015 values values values values values
etc \\//
1992 values

我查看了其他帖子并尝试了 reshape 和 asmatrix,但鉴于它是不均匀的系列,我不断收到此错误。

ValueError:新数组的总大小必须不变。

我真正想做的是,如果矩阵是奇数形状,则为缺失值插入 NaN。因此,如果 2017 年没有 11 月或 12 月的值,它们将为 NaN

如果有人能帮上忙,请告诉我

最佳答案

来源 DF:

In [159]: df
Out[159]:
val
date
1992-01-31 1.123077
1992-02-28 -2.174845
1992-03-31 -3.884848
1992-04-30 8.682919
1992-05-29 1.312976
1992-06-30 7.851080
1992-07-31 -3.192788
1992-08-31 -7.351976
1992-09-30 -6.782217
1992-10-30 -17.182738
1992-11-30 3.898782
1992-12-31 -26.190414
1993-01-29 2.233359
1993-02-26 6.709006

解决方法:

import calendar

In [158]: (df.assign(year=df.index.year, mon=df.index.month)
.pivot(index='year', columns='mon', values='val')
.rename(columns=dict(zip(range(13), calendar.month_name))))
Out[158]:
mon January February March April May June July August September October November December
year
1992 1.123077 -2.174845 -3.884848 8.682919 1.312976 7.85108 -3.192788 -7.351976 -6.782217 -17.182738 3.898782 -26.190414
1993 2.233359 6.709006 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN

更新: 或者更好更短的 version from @COLDSPEED :

In [164]: pd.pivot(df.index.year, df.index.month, df['val']) \
.rename(columns=calendar.month_name.__getitem__)
Out[164]:
date January February March April May June July August September October November December
date
1992 1.123077 -2.174845 -3.884848 8.682919 1.312976 7.85108 -3.192788 -7.351976 -6.782217 -17.182738 3.898782 -26.190414
1993 2.233359 6.709006 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN

关于python - 在 python 中将 Series reshape 为 Dataframe 矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47969456/

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