2017-06-13 59 views
1

我运行将多值列扩展到熊猫的新列

Python版本:2.7.12 | Anaconda 4.1.1(64位)| (默认情况下,2016年6月29日,11点07分13秒)[MSC v.1500 64位(AMD64)]熊猫版本:0.18.1 IPython的版本:4.2.0

在Windows 7 64.

什么会得到像

pd.DataFrame([[1,'a',1,'b',2,'c',3,'d',4], 
       [2,'e',5,'f',6,'g',7], 
       [3,'h',8,'i',9], 
       [4,'j',10]],columns=['ID','var1','var2','newVar1_1','newVar1_2','newVar2_1','newVar2_2','newVar3_1','newVar3_2']) 

一个数据帧从

pd.DataFrame([[1,'a',1], 
       [1,'b',2], 
       [1,'c',3], 
       [1,'d',4], 
       [2,'e',5], 
       [2,'f',6], 
       [2,'g',7], 
       [3,'h',8], 
       [3,'i',9], 
       [4,'j',10]],columns=['ID','var1','var2']) 

我会怎么做一个快速的方法是按ID,然后遍历GROUPBY物体上,使每个项目一个新的行将它附加在最初的emtpty上数据帧,但是这很慢,因为在实际情况下,起始数据帧的行数为数千。

有什么建议吗?

回答

1
df.set_index(['ID', df.groupby('ID').cumcount()]).unstack().sort_index(1, 1) 

    var1 var2 var1 var2 var1 var2 var1 var2 
     0  0  1 1  2 2  3 3 
ID            
1  a 1.0  b 2.0  c 3.0  d 4.0 
2  e 5.0  f 6.0  g 7.0 None NaN 
3  h 8.0  i 9.0 None NaN None NaN 
4  j 10.0 None NaN None NaN None NaN 

或多个完整的

d1 = df.set_index(['ID', df.groupby('ID').cumcount()]).unstack().sort_index(1, 1) 
d1.columns = d1.columns.to_series().map('new{0[0]}_{0[1]}'.format) 
d1.reset_index() 

    ID newvar1_0 newvar2_0 newvar1_1 newvar2_1 newvar1_2 newvar2_2 newvar1_3 newvar2_3 
0 1   a  1.0   b  2.0   c  3.0   d  4.0 
1 2   e  5.0   f  6.0   g  7.0  None  NaN 
2 3   h  8.0   i  9.0  None  NaN  None  NaN 
3 4   j  10.0  None  NaN  None  NaN  None  NaN 
+0

感谢@piRSquared。这很好! – akotronis