【发布时间】:2019-11-28 22:56:39
【问题描述】:
背景
我有以下示例 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) 但它并没有给我想要的输出
问题
如何实现我想要的输出?
【问题讨论】:
标签: regex python-3.x string pandas replace