2017-06-13 58 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