[英]pandas - get_dummies multiplied by quantities
I have a pandas.DataFrame
with Stockcode and quantity:我有一个pandas.DataFrame
与Stockcode及数量:
>>>df
StockCode Quantity
0 85123A 6
1 71053 6
2 84406B 8
3 84029G 6
4 84029E 6
I'm looking for a solution to get the pandas.get_dummies()
multiplied by the quantity.我正在寻找一种解决方案来让pandas.get_dummies()
乘以数量。
The output I'm expecting should look like that:我期待的输出应该是这样的:
>>>pd.get_dummies(df['StockCode']) ... --> * df['Quantity']
71053 84029E 84029G 84406B 85123A
0 0 0 0 0 6
1 6 0 0 0 0
2 0 0 0 8 0
3 0 0 6 0 0
4 0 6 0 0 0
I can do a for loop to multiply all the dummies by the quantity, but I'm hoping a more "pythonic" solution.我可以做一个 for 循环来将所有的假人乘以数量,但我希望有一个更“pythonic”的解决方案。
Does anyone know if there is better way to get those corrected dummies ?有谁知道是否有更好的方法来获得那些更正的假人?
Thanks谢谢
Larry拉里
df.reset_index().pivot('index','StockCode','Quantity').fillna(0)
Out[93]:
StockCode 71053 84029E 84029G 84406B 85123A
index
0 0.0 0.0 0.0 0.0 6.0
1 6.0 0.0 0.0 0.0 0.0
2 0.0 0.0 0.0 8.0 0.0
3 0.0 0.0 6.0 0.0 0.0
4 0.0 6.0 0.0 0.0 0.0
To fix your code修复您的代码
pd.get_dummies(df['StockCode']).mul(df.Quantity,0)
Out[97]:
71053 84029E 84029G 84406B 85123A
0 0 0 0 0 6
1 6 0 0 0 0
2 0 0 0 8 0
3 0 0 6 0 0
4 0 6 0 0 0
Or pd.get_dummies(df['StockCode']).values*df.Quantity.values[:,None]
或pd.get_dummies(df['StockCode']).values*df.Quantity.values[:,None]
This also works这也有效
df.StockCode.str.get_dummies().mul(df.Quantity, axis=0)
Reference参考
How to multiply each row in pandas dataframe by a different value 如何将熊猫数据框中的每一行乘以不同的值
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.get_dummies.html https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.get_dummies.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.