如何为Pandas中的每个逗号分隔值创建新行

2024-09-29 23:28:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个数据帧:

text                     text2           category 
sfsd sgvv                sfsdfdf         abc,xyz
zydf sefs sdfsd          drdg            yyy
dfsd dsrgd dggr          dgd             xyz
eter vxg wfe             fs              abc
dfvf ertet               dggdss          abc,xyz,bbb

我想要这样的输出:

text                     text2           category 
sfsd sgvv                sfsdfdf         abc
sfsd sgvv                sfsdfdf         xyz
zydf sefs sdfsd          drdg            yyy
dfsd dsrgd dggr          dgd             xyz
eter vxg wfe             fs              abc
dfvf ertet               dggdss          abc
dfvf ertet               dggdss          xyz
dfvf ertet               dggdss          bbb

基本上,在category列中为每两个或更多类别创建一个新行

我试过这个:

df1 = (df.assign(category = df['category'].str.split(','))
         .explode('category')
         .reset_index(drop=True))

但它似乎创造了比预期更多的行。在我最初的df中,我有很多列,不仅仅是text、text2和category

我的原始数据帧的屏幕截图

这里category=NER_Category

enter image description here

以下是代码的输出:

enter image description here


Tags: textdfabccategoryxyztext2sdfsdsfsd
2条回答

您仍然可以使用explode来执行此操作

(
    df.assign(category=df.category.str.split(','))
    .explode('category')
)

        text            text2   category
0       sfsd sgvv       sfsdfdf abc
0       sfsd sgvv       sfsdfdf xyz
1       zydf sefs sdfsd drdg    yyy
2       dfsd dsrgd dggr dgd     xyz
3       eter vxg wfe    fs      abc
4       dfvf ertet      dggdss  abc
4       dfvf ertet      dggdss  xyz
4       dfvf ertet      dggdss  bbb

这应该做到:

(df.set_index(df.columns.drop('category',1).tolist())['category']
   .str.split(',', expand=True)
   .stack()
   .reset_index()
   .rename(columns={0:'category'})
   .loc[:, df.columns]
)

              text    text2 category
0        sfsd sgvv  sfsdfdf      abc
1        sfsd sgvv  sfsdfdf      xyz
2  zydf sefs sdfsd     drdg      yyy
3  dfsd dsrgd dggr      dgd      xyz
4     eter vxg wfe       fs      abc
5       dfvf ertet   dggdss      abc
6       dfvf ertet   dggdss      xyz
7       dfvf ertet   dggdss      bbb

相关问题 更多 >

    热门问题