带Pandas的数据透视表

2024-10-03 11:24:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用pandas将一行表转换为12列150年的表。基本上,一年过去了,Y轴和月份在X轴上。你知道吗

我的df返回以下信息:

DATAFRAME RESULTS

如何使用第一列中的日期创建x轴上有年份,y轴上有12个月的表?你知道吗

for county in CntyList:
    for model in models:
        for num in range(0, 33):
            #Outfile = r'E:\\ClimateChange\\Tables\\Counties\\' + str(county) + r'_' + str(folder) + r'_' + str(model) + r'.csv'
            rows = concatDF.ix[num]
            print(rows)

Tags: in信息pandasdfformodelmodelsrange
1条回答
网友
1楼 · 发布于 2024-10-03 11:24:09

我不太清楚我们在问什么,因为它的重要是张贴一个原始数据(不是一个图像)以及您正在寻找的输出样本最小的例子。你知道吗

尽管如此,我还是尝试先为您重新创建一些假数据,然后以您所描述的方式对其进行透视。你知道吗

首先创建假数据

我假设你有1800行原始数据-从1950年开始的150年中,每行1个月。你知道吗

months = np.tile(np.arange(1,13), 150) * 10000
years = np.repeat(np.arange(1950, 2100), 12)
idx = months + years
df = pd.DataFrame(index=idx, data={'num' :np.random.rand(len(idx))})

原始数据输出

这是数据帧的头部-1950年的前5个月

            num
11950  0.324358
21950  0.577816
31950  0.133126
41950  0.707563
51950  0.667286

还有尾巴——2099年的最后5个月

             num
82099   0.103834
92099   0.920796
102099  0.302548
112099  0.298861
122099  0.958643

从索引创建日期时间

现在我们可以使用to_datetime函数将索引转换为时间戳

date = pd.to_datetime(idx, format='%m%Y')

将年和月转换为数据帧列

df['Year'] = date.year
df['Month'] = date.month

最后,对数据进行透视,得到一个包含150行和12列的表

df.pivot(index='Year', columns='Month')

有输出

            num                                                              \
Month        1         2         3         4         5         6         7    
Year                                                                          
1950   0.324358  0.577816  0.133126  0.707563  0.667286  0.214770  0.833923   
1951   0.727718  0.818254  0.132464  0.124236  0.074853  0.183405  0.387825   
1952   0.156100  0.968507  0.588337  0.410274  0.811571  0.790409  0.554290   
1953   0.313295  0.366085  0.442786  0.834929  0.565413  0.215566  0.395442   
1954   0.185577  0.498335  0.726637  0.209410  0.426887  0.487188  0.202640   


Month        8         9         10        11        12  
Year                                                     
1950   0.646929  0.622495  0.417010  0.718361  0.752805  
1951   0.531334  0.969626  0.556064  0.114697  0.212898  
1952   0.451180  0.488284  0.344732  0.054810  0.276036  
1953   0.338134  0.456241  0.647255  0.966014  0.865256  
1954   0.966250  0.870074  0.853948  0.411874  0.322245 

供您实施

使用to_datetime将索引转换为日期时间。将列yearmonth添加到数据帧中,然后对其进行透视。如果这是你想要的,请在评论中告诉我。你知道吗

相关问题 更多 >