gpt4 book ai didi

python - 在 Python 中将日期作为一行数据透视

转载 作者:太空宇宙 更新时间:2023-11-04 04:26:59 25 4
gpt4 key购买 nike

我保留的数据格式如下:

Region                    0              1              2             3
Date 2005-01-01 2005-02-01 2005-03-01 ....
East South Central 400 500 600
Pacific 100 200 150
.
.
Mountain 500 600 450

我需要旋转此表,使其看起来像:

0     Date           Region                     value
1 2005-01-01 East South Central 400
2 2005-02-01 East South Central 500
3 2005-03-01 East South Central 600
.
.
4 2005-03-01 Pacific 100
4 2005-03-01 Pacific 200
4 2005-03-01 Pacific 150
.
.

由于 DateRegion 彼此重叠,我不确定如何meltpivot围绕这些字符串,以便我可以获得所需的输出。

我该怎么做?

最佳答案

我认为这就是您正在寻找的解决方案。举例说明。

import pandas as pd
import numpy as np
N=100
regions = list('abcdef')
df = pd.DataFrame([[i for i in range(N)], ['2016-{}'.format(i) for i in range(N)],
list(np.random.randint(0,500, N)), list(np.random.randint(0,500, N)),
list(np.random.randint(0,500, N)), list(np.random.randint(0,500, N))])
df.index = ['Region', 'Date', 'a', 'b', 'c', 'd']
print(df)

这给出了

            0       1       2       3       4       5       6       7   \
Region 0 1 2 3 4 5 6 7
Date 2016-0 2016-1 2016-2 2016-3 2016-4 2016-5 2016-6 2016-7
a 96 432 181 64 87 355 339 314
b 360 23 162 98 450 78 114 109
c 143 375 420 493 321 277 208 317
d 371 144 207 108 163 67 465 130

将其转换为您想要的形式的解决方案是

df.transpose().melt(id_vars=['Date'], value_vars=['a', 'b', 'c', 'd'])

给出

        Date variable value
0 2016-0 a 96
1 2016-1 a 432
2 2016-2 a 181
3 2016-3 a 64
4 2016-4 a 87
5 2016-5 a 355
6 2016-6 a 339
7 2016-7 a 314
8 2016-8 a 111
9 2016-9 a 121
10 2016-10 a 124
11 2016-11 a 383
12 2016-12 a 424
13 2016-13 a 453
...
393 2016-93 d 176
394 2016-94 d 277
395 2016-95 d 256
396 2016-96 d 174
397 2016-97 d 349
398 2016-98 d 414
399 2016-99 d 132

关于python - 在 Python 中将日期作为一行数据透视,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53310781/

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