这是我的数据框(其中作者列中的值是逗号分隔的字符串):
authors book
Jim, Charles The Greatest Book in the World
Jim An OK book
Charlotte A book about books
Charlotte, Jim The last book
如何将其转换为长格式,如下所示:
authors book
Jim The Greatest Book in the World
Jim An OK book
Jim The last book
Charles The Greatest Book in the World
Charlotte A book about books
Charlotte The last book
我尝试将各个作者提取到列表中,authors = list(df['authors'].str.split(','))
,展平该列表,将每个作者与每本书相匹配,并为每次匹配构建一个新的字典列表。但这对我来说似乎不太Pythonic,我猜pandas 有一个更干净的方法来做到这一点。
在设置书籍索引后,您可以按列拆分作者,这将让您几乎一直到达那里。重命名列并对其进行排序以完成。
df.set_index('book').authors.str.split(',', expand=True).stack().reset_index('book')
book 0
0 The Greatest Book in the World Jim
1 The Greatest Book in the World Charles
0 An OK book Jim
0 A book about books Charlotte
0 The last book Charlotte
1 The last book Jim
并带你一路回家
df.set_index('book')\
.authors.str.split(',', expand=True)\
.stack()\
.reset_index('book')\
.rename(columns={0:'authors'})\
.sort_values('authors')[['authors', 'book']]\
.reset_index(drop=True)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)