简体   繁体   中英

Finding memberships in a pandas df with string splits

I have a DF of the form

df=pd.DataFrame(
    {
    'm':['A','B','C','D'],
    'e':['ME','ME_YOU','ME_YOU','YOU'],
    'city':['SF','SF','SF_NY','NY']
    }
)
##### gives:
m       e        city
A       ME       SF
B       ME_YOU   SF
C       ME_YOU   SF_NY
D       YOU      NY

and I would like to convert it another df with True False based on columns e and city according to the membership of each element of m . Something like:

m      ME      YOU      SF      NY
A      True    False    True    False
B      True    True     True    False
C      True    True     True    True
D      False   True     True    False

I can see a way to do it by concatenating a series, row by row, depending on each value. But this is not very elegant, so I was wondering if there is a better way to do it in pandas.

Thanks a lot in advance

We join the column with sep first, get_dummies

df=df.join(df[['e','city']].apply('_'.join,1).str.get_dummies('_').astype(bool))
   m       e   city     ME     NY     SF    YOU
0  A      ME     SF   True  False   True  False
1  B  ME_YOU     SF   True  False   True   True
2  C  ME_YOU  SF_NY   True   True   True   True
3  D     YOU     NY  False   True  False   True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM