微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何重塑此Pandas数据框?

如何解决如何重塑此Pandas数据框?

我在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()pd.unstack(),但是我什么都没得到。我也无法在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,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  

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。