[英]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.