1

I have a column formatted like this:

American express,Visa,Master Card,Diners
American express,Visa,Master Card,Bancomat
all
Visa,Master Card,Diners,Banco

I want to create different columns for each element with 1 or 0 if the given card is found in the list or not.

The expected results should be something like this:

Visa    American Express    Master Card   Diners    Bancomat
1       1                   1             1         0
1       1                   1             0         1
1       1                   1             1         1
1       0                   1             1         0

Is there a way in pandas to do so?

1 Answer 1

2

Use Series.str.get_dummies with processing all column by DataFrame.add with DataFrame.pop for extract column:

print (df)
                                          col
0    American express,Visa,Master Card,Diners
1  American express,Visa,Master Card,Bancomat
2                                         all
3            Visa,Master Card,Diners,Bancomat

df = df['col'].str.get_dummies(',')

df = df.add(df.pop('all'), axis=0)
#alternative
#df += df.pop('all')[:, None]
print (df)
   American express  Bancomat  Diners  Master Card  Visa
0                 1         0       1            1     1
1                 1         1       0            1     1
2                 1         1       1            1     1
3                 0         1       1            1     1
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.