简体   繁体   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?

I have an nxn column where two of columns as follows:我有一个 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

I want to create unique columns for unique values of item_x and item_y, and fill them with appropriate values from cost and cost2 columns.我想为 item_x 和 item_y 的唯一值创建唯一列,并用 cost 和 cost2 列中的适当值填充它们。 So the expected output would be:所以预期的 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

Any help would be much appreciated!任何帮助将非常感激!

I would do a concat on a pd.get_dummies :我会在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: 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.

相关问题 根据唯一列值创建列并填充 - Create columns based on unique column values and fill 如何创建熊猫列并根据另一列中的值填充值 - How to create pandas columns and fill with values according to values in another column Python pandas 根据一列的唯一值创建多列 - Python pandas create multiple columns based on unique values of one column 如何使用 pandas 根据第三列中的值创建一个包含来自一列或另一列的值的新列? - How do I create a new column with values from one column or another based on the value in a third column using pandas? 根据pandas中的另一个列值有条件地填充列值 - Conditionally fill column values based on another columns value in pandas 如何根据熊猫另一列中的唯一值创建升序值列 - How to create column of ascending values based on unique values in another column in pandas 如何根据 pandas 中的另一列中的值将列中的值放入一行中的新列中? - How to put values in a column into new columns in one row based on values in one another column in pandas? Pandas DataFrame:如何从另一列的数值中创建数值? - Pandas DataFrame: How do I create numerical values out of numerical values from another column? 如何根据另一列中的单元格值有条件地填充 Pandas 列 - How to Conditionally Fill Pandas Column based on Cell Values in another column 根据其他列 pandas 中的值填入列 - Fill in column based on values in other columns pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM