df = {1: [51, 379, 552, 2333, 2335, 4089, 4484], 2: [51, 379, 552, 1674, 1688, 2333, 3650, 4089, 4296, 4484], 5: [783, 909, 1052, 1138, 1147, 2676], 7: [171, 321, 959], 9: [3193], 10: [959], 11: [131,567,897,923],..........} df2 = pd.DataFrame.from_dict(df, orient='index') df2 = df2.stack().reset_index() df2.level_1=1 df2.pivot(index='level_0',columns=0,values='level_1').fillna(0)
This converts the dict into a data frame followed by stacking to get the user IDs and movie IDs in separate columns, then all the values ββof the unused column level_1 are equal to 1. The last statement creates a pivot table filling in nonexistent combinations with zeros.
source share