在 pandas 中,如何根据一列中的唯一值创建列,然后根据另一列中的值填充它?

Posted

技术标签:

【中文标题】在 pandas 中,如何根据一列中的唯一值创建列,然后根据另一列中的值填充它?【英文标题】:In pandas, how do I create columns out of unique values in one column, and then fill it based on values in another column? 【发布时间】:2020-09-10 00:52:38 【问题描述】:

我有一个 n x n 列,其中两列如下:

height  cost  item_x    cost2    item_y   weight
15      10    bat        45       mitt    2
19      12    ball       30       ball    4
24      13    gloves     25       gloves  6
22      14    bat        20       mitt    8

我想为 item_x 和 item_y 的唯一值创建唯一列,并用 cost 和 cost2 列中的适当值填充它们。所以预期的输出是:

height  bat_x  ball_x  gloves_x  mitt_y  ball_y  gloves_y   weight
15      10     0       0         45      0        0         2
19      0      12      0         0       30       0         4
24      0      0       13        0       0        25        6
22      14     0       0         20      30       0         8

任何帮助将不胜感激!

【问题讨论】:

【参考方案1】:

我会在pd.get_dummies 上做一个concat

# extract the suffixes `_x, _y`
suffixes = df.columns.str.extract('(_.*)$')[0]

# output
pd.concat([pd.get_dummies(df.iloc[:,i+1])
             .add_suffix(suffixes[i+1])
             .mul(df.iloc[:,i],axis=0) 
           for i in range(0,df.shape[1], 2)],
          axis=1
         )

输出:

   ball_x  bat_x  gloves_x  ball_y  gloves_y  mitt_y
0       0     10         0       0         0      45
1      12      0         0      30         0       0
2       0      0        13       0        25       0
3       0     14         0       0         0      20

【讨论】:

太棒了!另一个非常有用的答案。非常感谢!您能否向我解释一下 pd.concat 函数中的行在做什么?我有点困惑,因为这个 df 比列出的列更多 - 上面更新了表格

以上是关于在 pandas 中,如何根据一列中的唯一值创建列,然后根据另一列中的值填充它?的主要内容,如果未能解决你的问题,请参考以下文章