【问题标题】:Splitting a string ignoring case in Pandas在 Pandas 中拆分字符串忽略大小写
【发布时间】:2019-12-03 22:58:26
【问题描述】:

我需要做的是:

df[col].str.split(my_regexp, re.IGNORECASE, expand=True)

但是,pandas DataFrame.str.split 方法无法添加正则表达式标志。

由于我需要扩展结果,所以我不能做类似的事情

df.apply(lambda x: re.split(my_regexp, x[col], flags=re.IGNORECASE), axis=1, result='expand')

因为列表的长度不同。

我需要一种方法来使re.split返回所有相同长度的列表,或者在Series.str.split 方法中传递re.IGNORECASE。或者也许是更好的方法?

谢谢大家!

编辑:这里有一些数据可以更好地解释

series = pd.Series([
    'First paRt foo second part FOO third part',
    'test1 FoO test2', 
    'hi1 bar HI2',
    'This is a Test',
    'first baR second BAr third',
    'final'
])

应该返回正则表达式r'foo|bar'


    0               1               2
0   First paRt      second part     third part
1   test1           test2           None
2   hi1             HI2             None
3   This is a Test  None            None
4   first           second          third
5   final           None            None

【问题讨论】:

  • 您能否添加一些示例数据,以便我们自己尝试并为您提供答案?
  • 是否可以选择将my_regexp 写成小写然后使用:df[col].str.lower().str.split(my_regexp, expand=True)
  • 我添加了一些示例。这将是一个好主意,但不幸的是,我真的需要输出中的字符串相同
  • 上述 Erfran 解决方案也降低了结果的大小写。

标签: python regex pandas split series


【解决方案1】:

方法一:如果需要保留小写/大写:

series.apply(lambda x: ', '.join(re.split(r'foo|bar', x, flags=re.IGNORECASE)))\
      .str.split(', ', expand=True)

输出

                0              1            2
0     First paRt    second part    third part
1          test1           test2         None
2            hi1             HI2         None
3  This is a Test           None         None
4          first         second         third
5           final           None         None

小写/大写不成问题的方法2

如 cmets 中所述,使用 str.lower() 将您的系列广播为小写,然后使用 str.split

series.str.lower().str.split(r'foo|bar', expand=True)

输出

                0              1            2
0     first part    second part    third part
1          test1           test2         None
2            hi1             hi2         None
3  this is a test           None         None
4          first         second         third
5           final           None         None

方法3去除不必要的空格:

series.str.lower().str.split(r'foo|bar', expand=True).apply(lambda x: x.str.strip())

输出

                0            1           2
0      first part  second part  third part
1           test1        test2        None
2             hi1          hi2        None
3  this is a test         None        None
4           first       second       third
5           final         None        None

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-11
    • 1970-01-01
    • 2016-01-29
    • 1970-01-01
    • 2020-06-05
    • 2022-01-07
    相关资源
    最近更新 更多