繁体   English   中英

在 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?

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

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 列中的适当值填充它们。 所以预期的 output 将是:

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

任何帮助将非常感激!

我会在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
         )

Output:

   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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM