我在熊猫数据框中有一个“地址”列。我需要在python中将序数转换为第一个到第一个,第二个到第二个,等等。我尝试搜索解决方案,但没有成功。
我的数据框如下所示:-
print(newdf) :-
Address
0 2 fairgreen lane bolton callan
1 2 leix rd cabra dublin 7
2 7 sraid na mara 1st sea rd strandhill rd
Suppose the 3rd record has 1st sea road, it should be converted to first sea road. I am not sure how to pass the data frame column in the argument.
```python
The below code converts number to word.
num2words(42, to='ordinal') 'forty-second' num2words(42, to='cardinal') 'forty-two'
答案 0 :(得分:2)
这是一个很好的软件包,您可以将其pip安装到项目中,该项目会将序数转换为单词https://pypi.org/project/num2words/,此处的文档提供了许多有关如何使用它的良好信息。
答案 1 :(得分:1)
您可以从字符串中提取数字(即从42
中提取42nd
,然后将num2words
与ordinal=True
一起使用:
import re
from num2words import num2words
ordinalAsNumber = "42nd"
number = re.search('\d+', ordinalAsNumber)
ordinalAsString = num2words(number[0], ordinal=True)
print( ordinalAsString ) # forty-second
您可以像这样从字符串中提取所有序数:
text = "Text with several ordinals such as 42nd, 31st, and 5th as well as plain numbers such as 1, 2, 3."
numbers = re.findall('(\d+)[st|nd|rd|th]', text)
for n in numbers:
ordinalAsString = num2words(n, ordinal=True)
print( ordinalAsString )
输出:
forty-second
thirty-first
fifth
您可以用re.sub()
进行替换:
text = "Text with several ordinals such as 42nd, 31st, and 5th as well as plain numbers such as 1, 2, 3."
numbers = re.findall('(\d+)[st|nd|rd|th]', text)
newText = text
for n in numbers:
ordinalAsString = num2words(n, ordinal=True)
newText=re.sub(r"\d+[st|nd|rd|th]", ordinalAsString, text, 1)
print ( text )
print( newText )
输出:
# Text with several ordinals such as 42nd, 31st, and 5th as well as plain numbers such as 1, 2, 3.
# Text with several ordinals such as forty-secondd, thirty-firstt, and fifthh as well as plain numbers such as 1, 2, 3.