慕无忌1623718
假设以下数据帧: user name0 1 a1 1 b2 1 c3 1 d4 2 a5 2 b6 2 c7 3 d8 3 e9 3 f你可以GROUPBY用户,然后使用get_dummmies:import pandas as pd# create data-framedata = [[1, 'a'], [1, 'b'], [1, 'c'], [1, 'd'], [2, 'a'], [2, 'b'], [2, 'c'], [3, 'd'], [3, 'e'], [3, 'f']]df = pd.DataFrame(data=data, columns=['user', 'name'])# group and get_dummiesgrouped = df.groupby('user')['name'].apply(lambda x: '|'.join(x))print(grouped.str.get_dummies())输出 a b c d e fuser 1 1 1 1 1 0 02 1 1 1 0 0 03 0 0 0 1 1 1作为旁注,您可以在一行中完成所有操作:result = df.groupby('user')['name'].apply(lambda x: '|'.join(x)).str.get_dummies()