首页 > 解决方案 > 在 pandas 中用反引号解码对象

问题描述

import pandas as pd    
sr = pd.Series(["`1", "2", "`3", "4", None, None, None])

我有一个与上述对象非常相似的对象系列(len>10000)。我想保留非数字,但将数字转换为整数。我不确定如何处理似乎用反引号编码的数字。解决此问题的最佳方法是什么?

标签: pythonpandasdata-cleaning

解决方案


这是一个可能的解决方案:

sr = sr.str.replace('`', '').astype('float').astype('Int32')

您不能将字符串转换为可为空的整数。解决方法是首先将其转换为浮点数。这是结果系列:

0       1
1       2
2       3
3       4
4    <NA>
5    <NA>
6    <NA>
dtype: Int32

推荐阅读