如何从pandas数据框中删除带有正则表达式的答案中的点号:“(I)”、“(ii)”、“(iii)”?

2024-09-30 05:31:40 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个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'')

但代码不起作用。它从我的答案中删除我所有的答案。考虑成为收件人,我可以删除A,B。等,如果我单独给出,即_replace=r'[a.| b.| a.| b.]但是如果给出了模式,它就不起作用了

对于一个或多个带有正则表达式的数据帧,如何从a-Z和I中删除“(I)”、“(ii)”、“(iii)”和“(a)”、“(a)”、“a.”范围

范例

输入
(i) 这头牛有四条腿。牛吃草。牛给我们牛奶

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

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


Tags: 数据答案truepandas系统特性replace编号
2条回答

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

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

模式匹配:

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

Regex demo

如果你想匹配罗马数字,你可以看到this post

请你试试:

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.

regex ^\(?(?:[ivxlcdm]+|[a-zA-Z]+|[0-9]+)[).]的解释:

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

相关问题 更多 >

    热门问题