将多值列扩展到 pandas 中的新列

Expand multivalued column to new columns in pandas

我运行

Python 版本:2.7.12 |Anaconda 4.1.1(64 位)| (默认,2016 年 6 月 29 日,11:07:13)[MSC v.1500 64 位 (AMD64)] Pandas 版本: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 对象以从每个项目创建一个新行并将其附加到最初为空的数据帧上,但这很慢,因为在实际情况下起始数据框有几千个。

有什么建议吗?

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