熊猫在保持NA或NaN的同时将文本类型转换为int

时间:2019-12-20 13:46:02

标签: python pandas

如果我在dtype:object(文本)的pandas数据框中有货币列,其值如下:

34500 USD
34222 USD

如何将其转换为允许NaN或NA出现在列中的整数类型?

2 个答案:

答案 0 :(得分:2)

我们可以做str.strip

carDF['carPrice'] = pd.to_numeric(carDF['carPrice'].str.strip('USD'), errors='coerce', downcast='integer')

答案 1 :(得分:1)

解决方案:

carDF['carPrice'] = carDF['carPrice'].astype(str).str.replace(' USD','')
carDF['carPrice'] = pd.to_numeric(carDF['carPrice'], errors='coerce', downcast='integer').astype('Int64')

并且如果您的字符中有非ASCII空间,则仅当您打印单行时才能看到:

carDF['carPrice'][0]
'34500 \xa0USD'

比您必须使用的要多:

carDF['carPrice'] = carDF['carPrice'].astype(str).str.replace(u'\xa0USD', '')

here

所述

您必须运行0.24以上的熊猫版本

pip install pandas --upgrade

如果不适合您,则升级到最新的熊猫。