Pandas - get_dummies with value from another column

与世无争的帅哥 提交于 2019-12-06 14:38:03

问题


I have a dataframe like below. The column Mfr Number is a categorical data type. I'd like to preform get_dummies or one hot encoding on it, but instead of filling in the new column with a 1 if it's from that row, I want it to fill in the value from the quantity column. All the other new 'dummies' should remain a 0 on that row. Is this possible?

    Datetime            Mfr Number                quantity
0   2016-03-15 07:02:00 MWS0460MB                 1
1   2016-03-15 07:03:00 TM-120-6X                 3
2   2016-03-15 08:33:00 40.50699.0095             5
3   2016-03-15 08:42:00 40.50699.0100             1
4   2016-03-15 08:46:00 CXS-04T098-00-0703R-1025  10

回答1:


Do it in two steps:

dummies = pd.get_dummies(df['Mfr Number'])
dummies.values[dummies != 0] = df['Quantity']



回答2:


Check with str.get_dummies and mul

df.Number.str.get_dummies().mul(df.quantity,0)
   40.50699.0095  40.50699.0100    ...      MWS0460MB  TM-120-6X
0              0              0    ...              1          0
1              0              0    ...              0          3
2              5              0    ...              0          0
3              0              1    ...              0          0
4              0              0    ...              0          0
[5 rows x 5 columns]



回答3:


df = pd.get_dummies(df, columns = ['Mfr Number'])
for col in df.columns[2:]:
    df[col] = df[col]*df['quantity']


来源:https://stackoverflow.com/questions/55271858/pandas-get-dummies-with-value-from-another-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!