1

I'm trying to prep a csv for import into a survey tool from an exported csv from yet another tool. I need to map a singe column of values from one df into multiple columns to satisfy the checkbox of the other csv.

For example my starting df (df1) and target df (df2) look like:

import pandas as pd
df1 = pd.DataFrame({'user': ['Bob', 'Jane', 'Alice']})
df2 = pd.DataFrame({'Bob': [0,0,0], 'Jane': [0,0,0], 'Alice': [0,0,0]}) 

I've tried:

for value in df1["User"]:
    if value == "Bob":
        df2['Bob'] = 1
    elif value == "Jane":
        df2['Jane'] = 1
    elif value == "Alice":
        df2['Alice'] = 1

But I end up with a '1' in every row and column.

Result:


  Bob Jane Alice
0   1   1   1
1   1   1   1
2   1   1   1

I'm trying to create:

  Bob Jane Alice
0   1   0   0
1   0   1   0
2   0   0   1

What am I missing?

1 Answers1

0

Try using:

pd.get_dummies(df1["User"])
Yaakov Bressler
  • 9,056
  • 2
  • 45
  • 69