2 回答

TA貢獻1802條經(jīng)驗 獲得超10個贊
您可以使用explode和map:
df1 = df.explode('genres').sort_values('genres').rename(
columns={'genres' : 'genres_group'})\
.set_index('genres_group',append=True)
df1['genres'] = df1.index.get_level_values(0).map(df['genres'])
print(df1)
movie_id genres
genres_group
0 1 2 [1, 2]
1 1 3 [1, 3]
0 2 2 [1, 2]
2 2 4 [2, 4]
1 3 3 [1, 3]
2 4 4 [2, 4]

TA貢獻1815條經(jīng)驗 獲得超10個贊
這是你需要達到的結(jié)果嗎?
genre_group = pd.Series(df.apply(lambda x: pd.Series(x['genres']), axis=1).stack().reset_index(level=1, drop=True), name='genre_group') df = pd.concat([genre_group, df], axis = 1)
輸出:
添加回答
舉報