在Python中以日期为单位旋转数据

时间:2018-11-15 00:27:39

标签: python python-3.x pandas dataframe pivot-table

我所保留的数据格式可以使我根据以下日期进行调整:

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,以便获得所需的输出。

我该怎么办?

1 个答案:

答案 0 :(得分:1)

我认为这是您正在寻找的解决方案。以示例显示。

grep -E 'animal-06[0-9]' animallist.txt

这给出了

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'])