我正在使用一个公开可用的选举数据集,我已将其作为 df 导入 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
我想做这样的事情:
fips_code county total dem gop oth year
26041 Delta County 19064 9974 8763 327 2008
48295 Lipscomb County 1256 155 1093 8 2008
1127 Walker County 28652 7420 20722 510 2008
我四处搜索并找到了类似的东西,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
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
关于python - 在 Python 中熔化和旋转数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50848495/