在Python中熔化并旋转数据帧?

2024-05-12 19:12:15 发布

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

我正在处理一个公开的选举数据集,我把它作为一个数据集导入到Pandas中:

    fips_code   county              total_2008  dem_2008    gop_2008     oth_2008   total_2012  dem_2012    gop_2012    oth_2012    total_2016  dem_2016    gop_2016    oth_2016
0   26041       Delta County        19064       9974        8763        327         18043       8330        9533        180         18467       6431        11112       924
1   48295       Lipscomb County     1256        155         1093        8           1168        119         1044        5           1322        135         1159        28
2   1127        Walker County       28652       7420        20722       510         28497       6551        21633       313         29243       4486        24208       549

我想做这样的事情:

^{pr2}$

我到处找了找,发现了一些类似的东西,Stack and Pivot Dataframe in Python,但我不知道如何把它应用到我的问题上。在

我成功地完成了df的融化:

In [86]:
df_melt = pd.melt(df, id_vars=['fips_code', 'county'], value_name='num_votes')
df_melt.head()

Out [86]:
fips_code       county              variable    num_votes
0   26041       Delta County        total_2008  19064
1   48295       Lipscomb County     total_2008  1256
2   1127        Walker County       total_2008  28652
3   48389       Reeves County       total_2008  3077
4   56017       Hot Springs County  total_2008  2546

这就是我陷入困境的地方,因为我不知道这是一个从使用熔体开始的多步骤过程,还是有一个直接的方法从我的初始df到那里。我甚至不知道我应该使用什么函数,但它似乎涉及到pivot/stack/unstack?任何帮助都是非常感谢的。在


Tags: 数据dfcodenumtotaldeltawalkercounty
1条回答
网友
1楼 · 发布于 2024-05-12 19:12:15

这又是一个宽到长的问题。wide_to_long

pd.wide_to_long(df,['total','dem','gop','oth'],i=['fips_code','county'],j='Year',sep='_').reset_index()
Out[28]: 
   fips_code          county  Year  total   dem    gop  oth
0      26041     DeltaCounty  2008  19064  9974   8763  327
1      26041     DeltaCounty  2012  18043  8330   9533  180
2      26041     DeltaCounty  2016  18467  6431  11112  924
3      48295  LipscombCounty  2008   1256   155   1093    8
4      48295  LipscombCounty  2012   1168   119   1044    5
5      48295  LipscombCounty  2016   1322   135   1159   28
6       1127    WalkerCounty  2008  28652  7420  20722  510
7       1127    WalkerCounty  2012  28497  6551  21633  313
8       1127    WalkerCounty  2016  29243  4486  24208  549

相关问题 更多 >