在Pandas中将行数据拆分为列

时间:2018-08-28 20:07:05

标签: python-3.x pandas

我有如下数据框。

ID  Party   Votes

RS-24   D   31

RS-24   R   12

我想要做的是按照以下内容将行数据拆分为新列,以便我可以运行一些基本计算。

ID  D_Votes R_Votes

RS-24   31  12

有人知道我该怎么做吗?

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

set_indexunstack

df1=df.set_index(['ID','Party']).unstack().swaplevel(0,1,axis=1)
df1.columns=df1.columns.map('_'.join)
df1
Out[253]: 
       D_Votes  R_Votes
ID                     
RS-24       31       12