Skip to main content
 首页 » 编程设计

python之将行值转置到 pandas 数据框中现有的预定义列

2024年11月24日10kenshinobiy

我有一个按数量排序的数据框,为我提供每个名称的前 5 个类别,如下所示:

| Name | Category | Amount | 
|------|----------|--------| 
| Abel | A        | 9.2    | 
| Abel | B        | 3      | 
| Abel | C        | 2.5    | 
| Abel | E        | 2      | 
| Abel | X        | 0      | 
| Cain | W        | 93     | 
| Cain | A        | 2      |  
|------|----------|--------| 

这就是我最终想要的:

| Name | Cat 1 | Cat 2 | Cat 3 | Cat 4 | Cat 5 | 
|------|-------|-------|-------|-------|-------| 
| Abel | A     | B     | C     | E     | X     | 
| Cain | W     | A     | -     | -     |  -    | 
|------|-------|-------|-------|-------|-------| 

我尝试了 df.pivot("Name","Category") 但它将值(例如 A、B、...)设置为列名,但我希望将 5 列预定义为“Cat 1”改成“Cat 5”,所以我不确定现在该怎么做才能得到结果。此外,并非所有名称都有 5 行。例如Cain 只有前 2 名,这意味着 Cat 3、Cat 4 和 Cat5 列应该为空或“-”。有什么帮助吗?谢谢!

更新:

好的,例如如果我所有的名字只有 2 个类别记录,我仍然希望为前 5 个类别(即 Cat 1、Cat 2、Cat 3、Cat 4、Cat 5)获得 5 个新列。

现在如果我这样做

df["g"] = top5_jmi.groupby("Name").cumcount().add(1) 

如果我稍后旋转它,这只会给我 2 列。我怎样才能得到5列?例如。

| Name | Category | Amount | 
|------|----------|--------| 
| Abel | A        | 9.2    | 
| Abel | B        | 3      | 
| Cain | W        | 93     | 
| Cain | A        | 2      | 
|------|----------|--------| 
 
should still give me this: 
 
| Name | Cat 1 | Cat 2 | Cat 3 | Cat 4 | Cat 5 | 
|------|-------|-------|-------|-------|-------| 
| Abel | A     |  B    |   -   |   -   |   -   | 
| Cain | W     |  A    |   -   |   -   |   -   | 
|------|-------|-------|-------|-------|-------| 

请您参考如下方法:

使用:

#create counter column used for later columns names 
df['g'] = df.groupby('Name').cumcount().add(1) 
#filter top3 
df = df[df['g'] <= 5] 
#reshape by pivot 
df2 = (df.pivot('Name','g','Category') 
         .add_prefix('Type ') 
         .reset_index() 
         .rename_axis(None, axis=1) 
         .fillna('-')) 
print (df2) 
   Name Type 1 Type 2 Type 3 Type 4 Type 5 
0  Abel      A      B      C      E      X 
1  Cain      W      A      -      -      - 

编辑:使用 DataFrame.reindex添加缺失的列:

df['g'] = df.groupby('Name').cumcount().add(1) 
#filter top3 
df = df[df['g'] <= 5] 
#reshape by pivot 
df2 = (df.pivot('Name','g','Category') 
         .reindex(range(1, 6), axis=1) 
         .add_prefix('Type ') 
         .reset_index() 
         .rename_axis(None, axis=1) 
         .fillna('-')) 
print (df2) 
   Name Type 1 Type 2 Type 3 Type 4 Type 5 
0  Abel      A      B      -      -      - 
1  Cain      W      A      -      -      -