如何从 Pandas 数据帧中删除带有正则表达式的答案中的点数:"(i)"、"(ii)"'(iii)'?



假设,我有一个pandas数据帧,它由许多行的产品名称和描述其各自功能的列组成。它们添加了一些编号系统,如1.、2.、3.、…或a(、b(、c(。。。。或(i(、(ii(、(iii(、,。。。等等。现在我想在数据帧中删除它们。

df.replace(regex=True, inplace=True, to_replace=r'["(i*)"|i*.|(a-zA-Z).|("("a-zA-z")")]', value=r'')

但代码不起作用。它删除了答案中的所有i,例如consider变成consder,如果我单独给出,我可以删除a、b等,即to_replace=r'[a.|b.|a.|b.],但如果给出了模式,它就不起作用了。

如何删除"(I("、"(ii("、"(iii("one_answers"(a("、"(a("、"a."A.’的范围从A-Z到i,表示一个或多个正则表达式pandas数据帧?

示例

INPUT
(i(这头牛有四条腿。(ii(牛吃草。(iii(奶牛给我们挤奶。

a.这头牛有四条腿。b.牛吃草。c.奶牛给我们挤奶。

输出这头牛有四条腿。牛吃草。奶牛给我们挤奶。

请尝试一下:

df.replace(regex=True, inplace=True, to_replace=r'^(?(?:[ivxlcdm]+|[a-zA-Z]+|[0-9]+)[).]', value='')

输入:

(i) The cow has four legs.
(ii) The cow eats grass.
(iii) Cow gives us milk.
a.The cow has four legs.
b.The cow eats grass.
c.Cow gives us milk.
1.The cow has four legs.
2.The cow eats grass.
3.Cow gives us milk.
a)The cow has four legs.
b)The cow eats grass.
c)Cow gives us milk.

输出:

The cow eats grass.
Cow gives us milk.
The cow has four legs.
The cow eats grass.
Cow gives us milk.
The cow has four legs.
The cow eats grass.
Cow gives us milk.
The cow has four legs.
The cow eats grass.
Cow gives us milk.

正则表达式^(?(?:[ivxlcdm]+|[a-zA-Z]+|[0-9]+)[).]:的解释

  • ^表示字符串的开始
  • (?匹配零或一个左括号
  • (?:[ivxlcdm]+|[a-zA-Z]+|[0-9]+)可以分解为以下任意一种:
    • 与罗马数字匹配的[ivxlcdm]+
    • 与字母匹配的CCD_ 6
    • 与数字匹配的CCD_ 7
  • [).]匹配右括号或点

如果一个i字符只能有1次或多次(因此没有罗马数字(,您可以使用:

(?i+)|b(?:[A-Za-z]|d+).

模式匹配:

  • (?i+)匹配可选的(,然后是i字符和)的1+倍
  • |
  • b防止部分匹配的字边界
  • (?:非捕获组
    • [A-Za-z]匹配单个字符a-Za-z
    • |
    • d+匹配1+位数字
  • )关闭非捕获组
  • .匹配点

Regex演示

如果你想匹配罗马数字,你可以看到这篇文章。

最新更新