首页 > 解决方案 > 带有熊猫的列中的行内换行

问题描述

大熊猫有什么方法可以将列中的一行内的数据分开吗?行有多个数据,我的意思是,我按 col1 分组,结果是我有一个这样的 df:

    col1   Col2
0   1      abc,def,ghi
1   2      xyz,asd

and desired output would be:

    Col1    Col2
 0  1       abc
            def
            ghi
 1  2       xyz
            asd

谢谢

标签: python-3.xpandaslinefeed

解决方案


使用str.splitexplode

print (df.assign(Col2=df["Col2"].str.split(","))
         .explode("Col2"))

   col1 Col2
0     1  abc
0     1  def
0     1  ghi
1     2  xyz
1     2  asd

推荐阅读