gpt4 book ai didi

regex - 替换出生日期前几位数的 Pandas

转载 作者:行者123 更新时间:2023-12-02 00:51:37 24 4
gpt4 key购买 nike

背景

我有以下示例df

import pandas as pd
df = pd.DataFrame({'Birthdate':['This person was born Date of Birth: 5/6/1950 and other',
'no Date of Birth: nothing here',
'One Date of Birth: 01/01/2001 last here'],
'P_ID': [1,2,3],
'N_ID' : ['A1', 'A2', 'A3']}

)

df
Birthdate N_ID P_ID
0 This person was born Date of Birth: 5/6/1950 a... A1 1
1 no Date of Birth: nothing here A2 2
2 One Date of Birth: 01/01/2001 last here A3 3

目标

*BDAY*替换生日的前几位数字,例如 5/6/1950变成 *BDAY*1950
所需的输出
                                 Birthdate                 N_ID P_ID
0 This person was born Date of Birth: *BDAY*1950 a... A1 1
1 no Date of Birth: nothing here A2 2
2 One last Date of Birth: *BDAY*2001 last here A3 3

尝试过

python - Replace first five characters in a column with asterisks中,我尝试了以下代码: df.replace(r'Date of Birth: ^\d{3}-\d{2}', "*BDAY*", regex=True),但它并不能完全满足我的期望输出

问题

如何获得所需的输出?

最佳答案

尝试这个:

df['Birthdate'] = df.Birthdate.str.replace(r'[0-9]?[0-9]/[0-9]?[0-9]/', '*BDAY*')


Out[273]:
Birthdate P_ID N_ID
0 This person was born Date of Birth: *BDAY*1950... 1 A1
1 no Date of Birth: nothing here 2 A2
2 One Date of Birth: *BDAY*2001 last here 3 A3

关于regex - 替换出生日期前几位数的 Pandas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57121057/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com