gpt4 book ai didi

python - Pandas 堆栈日期矩阵值

转载 作者:行者123 更新时间:2023-12-01 09:05:04 25 4
gpt4 key购买 nike

我的数据格式是这样的:

year month 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 .. 31
1998 1 2.5 1 - - -2.5 - - - - - - - - - - - - - - 1.5
1998 2 2.5 1 - - -4.5 - - - - - - - - - - - - - - 1.5
1998 3 2.5 1 - - -3.5 - - - - - - - - - - - - - - 1.5
1998 4 2.5 1 - - -8.5 - - - - - - - - - - - - - - 1.5
1998 5 2.5 1 - - -1.5 - - - - - - - - - - - - - - 1.5
2001 5 2.5 1 - - -1.5 - - - - - - - - - - - - - - 1.5

说明:

-表示缺失值。

year 列是年份。

月份列是月份。

1 2 3 4 等等是日期列,所以这是日期时间格式矩阵。

预期输出:

date value
1998-01-01 2.5
1998-01-02 2.8
1998-01-03 - # when is ismissing and the date is exist it show
1998-01-31 -
...
2008-02-28 - #
2008-02-29 - # this year the Febulary get 29 days
2008-03-01 3.4
...
2008-04-30 - # missing value and the date exist.
2008-05-01 3.0

最佳答案

您所要求的几乎就是“un-pivot”,您的 DataFrame。解决这些类型问题的一般方法是使用某些版本的 meltstackunstack。这是使用stack的方法。

设置

df = pd.DataFrame({'year': {0: 1998, 1: 1998, 2: 1998, 3: 1998, 4: 1998, 5: 2001}, 'month': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 5}, '1': {0: 2.5, 1: 2.5, 2: 2.5, 3: 2.5, 4: 2.5, 5: 2.5}, '2': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}, '3': {0: '-', 1: '-', 2: '-', 3: '-', 4: '-', 5: '-'}, '4': {0: '-', 1: '-', 2: '-', 3: '-', 4: '-', 5: '-'}, '5': {0: '-', 1: '-', 2: '-', 3: '-', 4: '-', 5: '-'}, '6': {0: 2.5, 1: 4.5, 2: 3.5, 3: 8.5, 4: 1.5, 5: 1.5}, '7': {0: '-', 1: '-', 2: '-', 3: '-', 4: '-', 5: '-'}, '8': {0: '-', 1: '-', 2: '-', 3: '-', 4: '-', 5: '-'}, '9': {0: '-', 1: '-', 2: '-', 3: '-', 4: '-', 5: '-'}, '10': {0: '-', 1: '-', 2: '-', 3: '-', 4: '-', 5: '-'}, '11': {0: '-', 1: '-', 2: '-', 3: '-', 4: '-', 5: '-'}, '12': {0: '-', 1: '-', 2: '-', 3: '-', 4: '-', 5: '-'}, '13': {0: '-', 1: '-', 2: '-', 3: '-', 4: '-', 5: '-'}, '14': {0: '-', 1: '-', 2: '-', 3: '-', 4: '-', 5: '-'}, '15': {0: '-', 1: '-', 2: '-', 3: '-', 4: '-', 5: '-'}})

使用堆栈:

out = df.set_index(['year', 'month']).stack().reset_index()

pd.DataFrame({
'Date': pd.to_datetime(out.iloc[:, :3].astype(str).agg('-'.join, 1)),
'Value': out.iloc[:, 3]
})

        Date Value
0 1998-01-01 2.5
1 1998-01-02 1
2 1998-01-03 -
3 1998-01-04 -
4 1998-01-05 -
5 1998-01-06 2.5
.. ... ...
60 1998-05-01 2.5
61 1998-05-02 1
83 2001-05-09 -
84 2001-05-10 -
85 2001-05-11 -
86 2001-05-12 -
87 2001-05-13 -
88 2001-05-14 -
89 2001-05-15 -

关于python - Pandas 堆栈日期矩阵值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52129993/

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