title = ["Avatar", "Pirates of the Caribbean: At World's End", "Spectre", "The Dark Knight Rises", "John Carter" ]
genres = [[{"id": 28, "name": "Action"}, {"id": 12, "name": "Adventure"}, {"id": 14, "name": "Fantasy"}, {"id": 878, "name": "Science Fiction"}],
[{"id": 12, "name": "Adventure"}, {"id": 14, "name": "Fantasy"}, {"id": 28, "name": "Action"}],
[{"id": 28, "name": "Action"}, {"id": 12, "name": "Adventure"}, {"id": 80, "name": "Crime"}],
[{"id": 28, "name": "Action"}, {"id": 80, "name": "Crime"}, {"id": 18, "name": "Drama"}, {"id": 53, "name": "Thriller"}],
[{"id": 28, "name": "Action"}, {"id": 12, "name": "Adventure"}, {"id": 878, "name": "Science Fiction"}]]
df = pd.DataFrame({"title": title,
"genres": genres})
Расширение серии словарей:
genres_list = df["genres"].apply(lambda x: [y["name"] for y in x ]).explode()
genres_list
0 Action
0 Adventure
0 Fantasy
0 Science Fiction
1 Adventure
1 Fantasy
1 Action
2 Action
2 Adventure
2 Crime
3 Action
3 Crime
3 Drama
3 Thriller
4 Action
4 Adventure
4 Science Fiction
Name: genres, dtype: object
Расширение заголовков:
Каждый элемент в df["title"]
повторяется n_i
раз, где n_i
длина соответствующего словаря. См. документацию .
title_rep = df["title"].repeat(df["genres"].apply(lambda x: len(x)))
title_rep
0 Avatar
0 Avatar
0 Avatar
0 Avatar
1 Pirates of the Caribbean: At World's End
1 Pirates of the Caribbean: At World's End
1 Pirates of the Caribbean: At World's End
2 Spectre
2 Spectre
2 Spectre
3 The Dark Knight Rises
3 The Dark Knight Rises
3 The Dark Knight Rises
3 The Dark Knight Rises
4 John Carter
4 John Carter
4 John Carter
Name: title, dtype: object
Объединение:
pd.DataFrame({"title": title_rep,
"genres": genres_list})
Возвращает:
title genres
0 Avatar Action
0 Avatar Adventure
0 Avatar Fantasy
0 Avatar Science Fiction
1 Pirates of the Caribbean: At World's End Adventure
1 Pirates of the Caribbean: At World's End Fantasy
1 Pirates of the Caribbean: At World's End Action
2 Spectre Action
2 Spectre Adventure
2 Spectre Crime
3 The Dark Knight Rises Action
3 The Dark Knight Rises Crime
3 The Dark Knight Rises Drama
3 The Dark Knight Rises Thriller
4 John Carter Action
4 John Carter Adventure
4 John Carter Science Fiction