如何重塑此 Pandas 数据框?

How do I reshape this Pandas dataframe?

我在 Pandas 中有第一个数据帧,我正在尝试将其重塑为第二个数据帧以用于监督机器学习目的。 [foo,bar]代表一个数据点;每个 id 都有一个明确的标签 [dog,cat] 和多个数据点。最终数据框按最初给出的顺序包含最多 3 个数据点,使用截断或零填充来实现此目标。

   foo  bar  dog  cat   id
0  1.1  1.6    0    1   12
1  2.3  2.4    0    1   12
2  4.5  4.2    0    1   12
3  2.3  1.2    0    1   12
4  4.2  3.8    1    0  535
5  1.6  4.1    1    0  535
...
 id  foo1  bar1  foo2  bar2  foo3  bar3  dog  cat
 12   1.1   1.6   2.3   2.4   4.5   4.2    0    1
535   4.2   3.8   1.6   4.1     0     0    1    0
...

我试过打电话给 pd.pivot(), pd.stack(), and pd.unstack(), but I haven't gotten anywhere. I also haven't been able to find what I'm trying to do on the Pandas reshaping docs。如果我能得到任何帮助,我将不胜感激,因为我对编程相当缺乏经验。

使用pivot_table + cumcount:

df2 = (df.pivot_table(index='id', columns=df.groupby('id').cumcount().add(1), 
                      aggfunc='first', fill_value=0)
         .sort_index(axis=1, level=1))
df2 = (df2.set_axis([f'{x}{y}' for x, y in df2.columns], 
                    axis=1)
          .reset_index())
print(df2)

或者:

df2 = (df.assign(groups_id=df.groupby('id').cumcount().add(1))
         .set_index(['id', 'groups_id'])
         .unstack(fill_value=0).sort_index(level=1, axis=1))
df2 = (df2.set_axis([f'{x}{y}' for x, y in df2.columns], 
                    axis=1)
          .reset_index())
print(df2)

输出

    id  bar1  cat1  dog1  foo1  bar2  cat2  dog2  foo2  bar3  cat3  dog3  \
0   12   1.6     1     0   1.1   2.4     1     0   2.3   4.2     1     0   
1  535   3.8     0     1   4.2   4.1     0     1   1.6   0.0     0     0   

   foo3  bar4  cat4  dog4  foo4  
0   4.5   1.2     1     0   2.3  
1   0.0   0.0     0     0   0.0