Python panda 分列维护多行连续

问题描述 投票:0回答:1

我有下面的数据,并且想将 DES 拆分为 2 列。特殊字符后的文本到另一列。描述连续有非固定多行。

================================
    It        |        Desc
================================
0   coat      |      Bos @Target@                                                                 
                     B2 @Sfop re@
1   boots     |      Wos (DSW)
================================

我收到列必须与键长度相同的错误

import pandas as pd
# creating the df
item = ['coat','boots']
dec = ["Bos @Target@\n  B2 @Sfop re@", "Wos (DSW)"]
df = pd.DataFrame(item, columns=   ['It'])
df['Desc'] = dec
print(df)
df[["Desc", "Ret"]] =   df["Desc"].str.findall("\w+").apply(pd.Series)

需要输出

================================
    It      |    Desc    |    Ret
================================
0  coat     |    Bos     |   @Target@                                        
                 B2          @Sfop re@
1  boots    |    Wos     |   (DSW)
================================
python pandas
1个回答
0
投票

您可以使用

str.extractall
来获取两部分:

df['Desc'].str.extractall(r'([^\n]+) ([@(][^\n]+)')

            0          1
  match                 
0 0       Bos   @Target@
  1        B2  @Sfop re@
1 0       Wos      (DSW)

然后,以换行符作为分隔符再次聚合:

df[['Desc', 'Ret']] = (df['Desc'].str.extractall('([^\n]+) ([@(][^\n]+)')
                       .groupby(level=0).agg('\n'.join)
                       )

输出:

      It       Desc                  Ret
0   coat  Bos\n  B2  @Target@\n@Sfop re@
1  boots        Wos                (DSW)
© www.soinside.com 2019 - 2024. All rights reserved.