我正在处理一个公开的选举数据集,我把它作为一个数据集导入到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?任何帮助都是非常感谢的。在
这又是一个宽到长的问题。wide_to_long
相关问题 更多 >
编程相关推荐