【问题标题】:How do I reshape this Pandas dataframe? [closed]如何重塑这个 Pandas 数据框? [关闭]
【发布时间】:2020-10-18 20:30:49
【问题描述】:

我有 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 上找到我想要做的事情。如果我能得到任何帮助,我将不胜感激,因为我对编程缺乏经验。

【问题讨论】:

  • 请从intro tour 重复on topichow to ask。 “我应该如何设计这个系统?”与 Stack Overflow 无关。您必须诚实地尝试解决方案,然后就您的实施提出具体问题。此外,为了符合本网站的目的,不接受文字图像。尤其是,由于您尚未指定您打算如何使用数据框,因此设计纯属推测。
  • 感谢您的反馈!在此期间,我将着手编辑我的问题。
  • @Prune ,请您看看我的问题现在是否与该社区有关?非常感谢您的反馈。

标签: python pandas reshape


【解决方案1】:

使用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  

【讨论】:

    猜你喜欢
    • 2019-05-19
    • 1970-01-01
    • 2017-11-26
    • 2012-12-10
    • 2020-04-19
    • 1970-01-01
    • 2017-04-23
    • 2021-08-09
    • 1970-01-01
    相关资源
    最近更新 更多