在pandas系列中按“||”拆分

3

我正在尝试使用 || 进行分割。

ser=pd.Series(['there a guy || I will have a bite || no can do','I can do || more'])
ser.str.split('||')

我应该得到的输出是[['有个人', '我会咬一口', '不行'], ['我能做', '更多']],但我得到的是
0    [, t, h, e, r, e, s,  , a,  , g, u, y,  , |, |...
1    [, I,  , c, a, n,  , d, o,  , |, |,  , m, o, r...
dtype: object
3个回答

3

||运算符在处理时与正则表达式类似,因此需要通过\进行转义:

a = ser.str.split('\|\|')
print (a)
0    [there a guy ,  I will have a bite ,  no can do]
1                                  [I can do ,  more]
dtype: object

1
为了避免转义,我建议使用字符类代替:
ser.str.split(r'[|]{2}')

0    [there a guy ,  I will have a bite ,  no can do]
1                                  [I can do ,  more]
dtype: object

如果您需要转义字符,可以使用re.escape函数来实现,无需手动转义。

import re
ser.str.split(re.escape('||'))

0    [there a guy ,  I will have a bite ,  no can do]
1                                  [I can do ,  more] 

1
如果您想要多列:
>>> ser.str.split('\|\|',expand=True)
              0                     1           2
0  there a guy    I will have a bite    no can do
1     I can do                   more        None
>>> 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接