我在 pandas 数据框中有一列非常大的电话号码,它们采用浮点格式:3.52831E+11
。还存在 NaN。
我正在尝试将数字转换为 int,但它抛出了 NaN 无法转换为 int 的错误。很公平。但我似乎无法解决这个问题。
这是一个示例:
df = pd.DataFrame({'number':['3.578724e+11','3.568376e+11','3.538884e+11',np.NaN]})
number
0 3.578724e+11
1 3.568376e+11
2 3.538884e+11
3 NaN
# My first attempt: here's where I try to convert them to int() however I get 'cannot convert float NaN to integer'.
df['number'] = [int(x) for x in df['number'] if isinstance(x, float)]
# I have also tried the below, but I get SyntaxError: invalid syntax.
df['number'] = [int(x) for x in df['number'] if x not None]
# and then this one, but the error is: TypeError: must be real number, not str
df['number'] = [int(x) for x in df['number'] if not math.isnan(x) and isinstance(x, float)]
我很感激对此的一些指示。我认为至少其中之一会起作用。
谢谢大家
最佳答案
从 pandas 0.24+ 开始,我们有 Nullable Integer Type 。第一步是将字符串(对象)转换为 float,然后转换为可为空的 int:
df.astype('float').astype(pd.Int64Dtype())
number
0 357872400000
1 356837600000
2 353888400000
3 NaN
作为简写,您也可以这样做,
df.astype('float').astype('Int64')
number
0 357872400000
1 356837600000
2 353888400000
3 NaN
<小时/>
在旧版本上,您唯一的选择是删除 NaN 并进行转换:
df.dropna(subset=['number']).astype({'number':float}).astype({'number':int})
number
0 357872400000
1 356837600000
2 353888400000
关于python - 将一系列 float 转换为 int - 列表中的某些 NaN 导致错误 'cannot convert float NaN to integer' 。如何跳过 NaN?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56602596/