Python 根据数据帧中序号的存在进行迭代和更新

Python 根据数据帧中序号的存在进行迭代和更新,python,pandas,Python,Pandas,我有一个包含地址列的数据框。我的数据框如下所示。我需要首先检查数据帧中是否有序号,如果有,我需要将其转换为单词。例如:- 3号索引的地址为19号院gorey公寓,应转换为19号院gorey公寓 我已经编写了查找序数并转换为word的代码。但我无法将更新的记录保存在原始数据帧中。更改只应在具有序号的特定记录上进行,其余数据帧应保持原样 代码给出的输出为:- 戈里十九苑公寓 斯莱德纳马拉第一海路斯特拉德希尔路7号 我的原始数据帧-newdf 地址 博尔顿卡伦费尔格林巷02号 都柏林卡布拉莱克斯路12

我有一个包含地址列的数据框。我的数据框如下所示。我需要首先检查数据帧中是否有序号,如果有,我需要将其转换为单词。例如:-

3号索引的地址为19号院gorey公寓,应转换为19号院gorey公寓

我已经编写了查找序数并转换为word的代码。但我无法将更新的记录保存在原始数据帧中。更改只应在具有序号的特定记录上进行,其余数据帧应保持原样

代码给出的输出为:- 戈里十九苑公寓 斯莱德纳马拉第一海路斯特拉德希尔路7号

我的原始数据帧-newdf
地址
博尔顿卡伦费尔格林巷02号
都柏林卡布拉莱克斯路12号7
2都柏林巴利库伦假日酒店woodale view 2 24
戈里第19宫3号公寓
进口稀土
从num2words导入num2words
对于索引,newdf.iterrows()中的行:
numbers=re.findall(“(\d+)(:st | nd | rd | th)”,第['Address'行)
对于n个数字:
序号字符串=num2words(n,序号=True)
newText=re.sub(r“(\d+)(:st | nd | rd | th)”,序号字符串,第['Address'行)
打印(新文本)
我的预期结果是:-
地址
博尔顿卡伦费尔格林巷02号
都柏林卡布拉莱克斯路12号7
2都柏林巴利库伦假日酒店woodale view 2 24
戈里第十九宫3号公寓
IIUC可与自定义函数一起使用

from num2words import num2words
import pandas as pd

df = pd.DataFrame(['2 fairgreen lane bolton callan',
                   '2 leix rd cabra dublin 7',
                   '2nd woodale view ballycullen 15th',
                   'apartment 19th court 20th gorey'], columns=['Address'])

def str_replace(x):
    number = x.group(1)
    extract_num = re.findall(r'\d+', number)[0]
    return num2words(extract_num, ordinal=True)

df['Address'] = df.Address.str.replace(r'(\d+(st|nd|rd|th))', str_replace)

# print(df.Address)

0                2 fairgreen lane bolton callan
1                      2 leix rd cabra dublin 7
2     second woodale view ballycullen fifteenth
3    apartment nineteenth court twentieth gorey
Name: Address, dtype: object