python - 将 Pandas 列中的阿拉伯数字转换为整数
问题描述
我接受了一项调查以供分析。不幸的是,一些参与者使用阿拉伯/波斯数字来填充一些值。例如:
import pandas as pd
pd.DataFrame(["24", "۱۲", "45", "۳۲"], columns=["age"])
我想要的是将所有值转换为 Python 整数:
[24, 12, 45, 32]
什么是最规范/最有效的方式来做到这一点
解决方案
首先通过您的号码申请unidecode
,然后使用pd.to_numeric
pip install unidecode
from unidecode import unidecode
df['numbers'] = pd.to_numeric(df.age.apply(unidecode), errors='coerce')
age numbers
0 24 24
1 ۱۲ 12
2 45 45
3 ۳۲ 32