J'ai un dataframe qui ressemble à ce qui suit:
publication_title authors type ...
title 1 ['author1', 'author2', 'author3'] proceedings
title 2 ['author4', 'author5'] collections
title 3 ['author6', 'author7'] books
.
.
.
Ce que je veux faire, c'est prendre la colonne `` auteurs '' et diviser la liste à l'intérieur en plusieurs lignes en dupliquant toutes les autres colonnes, et je veux également stocker les résultats dans une nouvelle colonne nommée: `` auteur '' et conserver la colonne d'origine .
Ce qui suit décrit exactement ce que je veux réaliser:
publication_title authors author type ...
title 1 ['author1', 'author2', 'author3'] author1 proceedings
title 1 ['author1', 'author2', 'author3'] author2 proceedings
title 1 ['author1', 'author2', 'author3'] author3 proceedings
title 2 ['author4', 'author5'] author4 collections
title 2 ['author4', 'author5'] author5 collections
title 3 ['author6', 'author7'] author6 books
title 3 ['author6', 'author7'] author7 books
.
.
.
J'ai essayé d'y parvenir en utilisant la méthode d'explosion de pandas DataFrame mais je ne trouve pas de moyen de stocker les résultats dans une nouvelle colonne.
Merci pour l'aide.
Depuis que pandas 0.25.0
nous avons la explode
méthode. Tout d'abord, nous dupliquons la authors
colonne et la renommons en même temps en utilisant, assign
puis nous éclatons cette colonne en lignes et dupliquons les autres colonnes:
df.assign(author=df['authors']).explode('author')
Production
publication_title authors type author
0 title_1 [author1, author2, author3] proceedings author1
0 title_1 [author1, author2, author3] proceedings author2
0 title_1 [author1, author2, author3] proceedings author3
1 title_2 [author4, author5] collections author4
1 title_2 [author4, author5] collections author5
2 title_3 [author6, author7] books author6
2 title_3 [author6, author7] books author7
Si vous souhaitez supprimer l'index dupliqué, utilisez reset_index
:
df.assign(author=df['authors']).explode('author').reset_index(drop=True)
Production
publication_title authors type author
0 title_1 [author1, author2, author3] proceedings author1
1 title_1 [author1, author2, author3] proceedings author2
2 title_1 [author1, author2, author3] proceedings author3
3 title_2 [author4, author5] collections author4
4 title_2 [author4, author5] collections author5
5 title_3 [author6, author7] books author6
6 title_3 [author6, author7] books author7
Este artículo se recopila de Internet, indique la fuente cuando se vuelva a imprimir.
En caso de infracción, por favor [email protected] Eliminar
Déjame decir algunas palabras