所以我的意见是:
Col1 Col2 Col3 Col4
0 123 abc,def,ghi Country1 XXX
1 456 pqr,stu Country2 XX
2 789 xyz Country2 YY
我希望我的输出为:
Col1 Col2 Col3 Col4
0 abc 123 Country1 XXX
1 def 123 Country1 XXX
2 ghi 123 Country1 XXX
3 pqr 456 Country2 XX
4 stu 456 Country2 XX
5 xyz 789 Country2 YY
什么是最pythonic的方式来做这个?谢谢你!
解决方法:
您可以使用str.split
和stack
将join
系列创建为原始DataFrame:
print (df.Col2
.str
.split(',',expand=True)
.stack()
.reset_index(drop=True, level=1)
.rename('Col2'))
0 abc
0 def
0 ghi
1 pqr
1 stu
2 xyz
Name: Col2, dtype: object
print (df.drop('Col2', axis=1)
.join
(
df.Col2
.str
.split(',',expand=True)
.stack()
.reset_index(drop=True, level=1)
.rename('Col2')
))
Col1 Col3 Col4 Col2
0 123 Country1 XXX abc
0 123 Country1 XXX def
0 123 Country1 XXX ghi
1 456 Country2 XX pqr
1 456 Country2 XX stu
2 789 Country2 YY xyz
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。