How to do pd.get_dummies or other ways?

给你一囗甜甜゛ 提交于 2019-12-04 14:59:22

A bit of str.split and pd.get_dummies magic, inspired by Scott Boston and improved (from original version) thanks to JohnE.

df = df.set_index('id').source.str.get_dummies(',')
df.columns = df.columns.str.split().str[0].str.lower()
df = df.add_prefix('source_').reset_index()

print(df)
                     id  source_bar  source_cash  source_dtot  source_dtp  \
0  AV4MdG6Ihowv-SKBN_nB           0            0            0           1   
1  AV4Mc2vNhowv-SKBN_Rn           0            1            0           0   
2  AV4MeisikOpWpLdepWy6           1            0            0           1   
3  AV4MeRh6howv-SKBOBOn           0            1            0           0   
4  AV4Mezwchowv-SKBOB_S           1            0            1           0   
5  AV4MeB7yhowv-SKBOA5b           1            0            0           1   

   source_food  
0            1  
1            1  
2            0  
3            1  
4            0  
5            0  

You could also do this: What I am doing is splitting the "Source" column and creating new rows.Then I call get_dummies on the source column, then groupby the "id" column.

data_vec = pd.DataFrame(pd.concat([pd.Series(row['id'], row['source'].split(','))              
                    for _, row in data_vec.iterrows()])).reset_index()
data_vec.columns = ['source','id']

which gives:

    source           id
0   DTP     AV4MdG6Ihowv-SKBN_nB
1   FOOD    AV4MdG6Ihowv-SKBN_nB
2   Cash 1  AV4Mc2vNhowv-SKBN_Rn
3   FOOD    AV4Mc2vNhowv-SKBN_Rn
4   DTP     AV4MeisikOpWpLdepWy6
5   Bar     AV4MeisikOpWpLdepWy6
6   Cash 1  AV4MeRh6howv-SKBOBOn
7   FOOD    AV4MeRh6howv-SKBOBOn
8   DTOT    AV4Mezwchowv-SKBOB_S
9   Bar     AV4Mezwchowv-SKBOB_S
10  DTP     AV4MeB7yhowv-SKBOA5b
11  Bar     AV4MeB7yhowv-SKBOA5b

then call get_dummies() on the source column:

result = pd.concat([data_vec.get(['id']),
                           pd.get_dummies(data_vec['source'], prefix='source')],axis=1)

result.groupby('id').sum().reset_index()

Which gives:

          id           source_Bar   source_Cash 1   source_DTOT source_DTP  source_FOOD
0   AV4Mc2vNhowv-SKBN_Rn    0               1              0        0            1
1   AV4MdG6Ihowv-SKBN_nB    0               0              0        1            1
2   AV4MeB7yhowv-SKBOA5b    1               0              0        1            0
3   AV4MeRh6howv-SKBOBOn    0               1              0        0            1
4   AV4MeisikOpWpLdepWy6    1               0              0        1            0
5   AV4Mezwchowv-SKBOB_S    1               0              1        0            0
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!