Actually,My problem is based on the :
Is there a faster way to update dataframe column values based on conditions?
So,the data should be:
import pandas as pd
import io
t="""
AV4MdG6Ihowv-SKBN_nB DTP,FOOD
AV4Mc2vNhowv-SKBN_Rn Cash 1,FOOD
AV4MeisikOpWpLdepWy6 DTP,Bar
AV4MeRh6howv-SKBOBOn Cash 1,FOOD
AV4Mezwchowv-SKBOB_S DTOT,Bar
AV4MeB7yhowv-SKBOA5b DTP,Bar
"""
data_vec=pd.read_csv(io.StringIO(t),sep='\s{2,}',names=['id','source'])
data_vec
This is the data_vec:
id source
0 AV4MdG6Ihowv-SKBN_nB DTP,FOOD
1 AV4Mc2vNhowv-SKBN_Rn Cash 1,FOOD
2 AV4MeisikOpWpLdepWy6 DTP,Bar
3 AV4MeRh6howv-SKBOBOn Cash 1,FOOD
4 AV4Mezwchowv-SKBOB_S DTOT,Bar
5 AV4MeB7yhowv-SKBOA5b DTP,Bar
If I want the result like follow:(It means how to vectorize the mutipletags or categories ?)
_id source_Cash 1 source_DTOT source_DTP Food Bar
0 AV4MdG6Ihowv-SKBN_nB 0 0 1 1 0
1 AV4Mc2vNhowv-SKBN_Rn 1 0 0 1 0
2 AV4MeisikOpWpLdepWy6 0 0 1 0 1
3 AV4MeRh6howv-SKBOBOn 1 0 0 1 0
4 AV4Mezwchowv-SKBOB_S 0 1 0 0 1
5 AV4MeB7yhowv-SKBOA5b 0 0 1 0 1
If it is duplicate, warn me to delete!
A bit of
str.split
andpd.get_dummies
magic, inspired by Scott Boston and improved (from original version) thanks to JohnE.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.
which gives:
then call get_dummies() on the source column:
Which gives: