我有一个包含许多列的数据帧,其中一列如下所示:

data = {'Product': ['Product A', 'Product B', 'Product C (discontinued in March 2021)', 'Product D', 'Product E (discontinued on 30 April 2004)']}

df = pd.DataFrame(data)

我试着编写了一段代码,它遍历列的每一行,在方括号中标识年份(如果适用),并将方括号中的文本替换为下面的'discont. '+the year identified.因此,对于'Product C',它应该更改为Product C (discont. 2021).

def amend_vals(value):
    pattern = r'\((\d{4})\)'  # Regex pattern to capture the year inside brackets
    match = re.search(pattern, value)
    if match:
        year = match.group(1)
        return re.sub(pattern, '(discont. ' + year + ')', value)
    else:
        return value

df['Product'] = df['Product'].apply(amend_vals)

不过,这似乎并不管用.有谁有办法修好它吗?

推荐答案

使用以下正则表达式替换:

df['Product'].str.replace(r'\([^(]+(\d{4})\)', rf'(discont. \1)', regex=True)

0                    Product A
1                    Product B
2    Product C (discont. 2021)
3                    Product D
4    Product E (discont. 2004)
Name: Product, dtype: object

Python相关问答推荐

Class_weight参数不影响RandomForestClassifier不平衡数据集中的结果

比较两个二元组列表,NP.isin

TARete错误:类型对象任务没有属性模型'

时间序列分解

Python库:可选地支持numpy类型,而不依赖于numpy

在Wayland上使用setCellWidget时,try 编辑QTable Widget中的单元格时,PyQt 6崩溃

ODE集成中如何终止solve_ivp的无限运行

OR—Tools中CP—SAT求解器的IntVar设置值

把一个pandas文件夹从juyter笔记本放到堆栈溢出问题中的最快方法?

根据列值添加时区

lityter不让我输入左边的方括号,'

如何防止Pandas将索引标为周期?

python中csv. Dictreader. fieldname的类型是什么?'

从列表中获取n个元素,其中list [i][0]== value''

如何将相同组的值添加到嵌套的Pandas Maprame的倒数第二个索引级别

如何在Python中从html页面中提取html链接?

如何在Polars中创建条件增量列?

Stats.ttest_ind:提取df值

Groupby并在组内比较单独行上的两个时间戳

基于2级列表的Pandas 切片3级多索引