【问题标题】:Remove all characters before a pipe and also remove pipe using regex in python删除管道之前的所有字符,并在 python 中使用正则表达式删除管道
【发布时间】:2020-04-26 11:36:16
【问题描述】:

您好,我正在工作,我正在使用 pandas 并尝试删除此 csv 文件中此管道之前的所有字符。用管道替换分号也会很有帮助。

Size| Medium; Large; Xlarge; 2Xlarge; 3Xlarge; 4Xlarge; 5xXlarge; 
Size| Medium; Large; Xlarge; 2Xlarge; 3Xlarge; 4Xlarge; 5xlarge; 
Sizes| Small - ( only one mic tab); Medium; Large; Xlarge; 2Xlarge; 3Xlarge; 4Xlarge; 5Xlarge; 
Sizes| Small - ( only one mic tab); Medium; Large; Xlarge; 2Xlarge; 3Xlarge; 4Xlarge; 5Xlarge; 

这是我一直在尝试的方法,但在逃离管道时遇到了麻烦。

df['Variations'] = df['Variations'].replace(regex=r'/\|$', value='')

我需要得到这个

Medium|Large|Xlarge|2Xlarge|3Xlarge|4Xlarge|5xXlarge 
Medium|Large|Xlarge|2Xlarge|3Xlarge|4Xlarge|5xlarge

【问题讨论】:

  • 您能否展示这些示例的预期输出,最好不要在屏幕截图中(易于复制/粘贴)
  • 可能,data['Variations'].str.replace(r'^[^|]*\|\s*', '').str.replace(';', '|', regex=False)
  • Sizes| Small - ( only one mic tab); Medium; Large; Xlarge; 2Xlarge; 3Xlarge; 4Xlarge; 5Xlarge; 这样的行呢?根本没有预期的输出?
  • 非常感谢您的成功。我只需要最后摆脱最后一个管道。谢谢|
  • df['Variations'] = df['Variations'].map(lambda x: str(x)[:-2]) 我在另一篇文章中添加了这个,再次感谢您。

标签: python regex pandas dataframe e-commerce


【解决方案1】:

你可以使用

data['Variations'] = data['Variations'].str.replace(r'^[^|]*\|\s*|;\s*$', '').str.replace('\s*;\s*', '|')

.replace(r'^[^|]*\|\s*|;\s*$', '') 将删除从字符串开头到第一个 | 的所有子字符串,包括它以及任何后续的空白字符和最后的 ;(末尾带有任何 0+ 空白),.replace('\s*;\s*', '|') 将替换所有; 分号周围的任何空格都带有管道字符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多