我有一个这样的数据框:

data = np.array([["userA","event2, event3"],
            ['userB',"event3, event4"],
            ['userC',"event2"]])

data = pd.DataFrame(data)

        0         1
0   userA   "event2, event3"
1   userB   "event3, event4"
2   userC   "event2"


现在我想得到一个像这样的数据框:

       0    event2      event3      event4
0   userA     1           1
1   userB                 1           1
2   userC     1


有人可以帮忙吗?

最佳答案

似乎您需要将get_dummies替换为0来清空string

df = data[[0]].join(data[1].str.get_dummies(', ').replace(0, ''))
print (df)
       0 event2 event3 event4
0  userA      1      1
1  userB             1      1
2  userC      1


详情:

print (data[1].str.get_dummies(', '))
   event2  event3  event4
0       1       1       0
1       0       1       1
2       1       0       0

10-04 19:00