本文介绍了将浮点数转换为具有数字和nan的列的整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python 3.6和Pandas 1.0.3.

I'm working with Python 3.6 and Pandas 1.0.3.

我想将浮点数从"A"列转换为int ...此列具有一些nan值.

I would like to convert the floats from column "A" to int... This column has some nan values.

因此,我遵循了此帖子使用@jezrael的解决方案.

So i followed this post with the solution of @jezrael.

但是出现以下错误:"TypeError:无法安全地将非等效的float64强制转换为int64"

But I get the following error:"TypeError: cannot safely cast non-equivalent float64 to int64"

这是我的代码

import pandas as pd
import numpy as np

data = {'timestamp': [1588757760.0000, 1588757760.0161, 1588757764.7339, 1588757764.9234], 'A':[9087.6000, 9135.8000, np.nan, 9102.1000], 'B':[0.1648, 0.1649, '', 5.3379], 'C':['b', 'a', '', 'a']}
df = pd.DataFrame(data)
df['A'] = pd.to_numeric(df['A'], errors='coerce').astype('Int64')
print(df)

我错过了什么吗?

推荐答案

您的问题是您拥有 true 浮点数,而不是浮点数形式的整数.因此出于安全原因,大熊猫不会将其转换,因为您会获得 other 值.

Your problem is that you have true float numbers, not integers in the float form. So for safety reasons pandas will not convert them, because you would be obtained other values.

因此,您首先需要将它们四舍五入为整数,然后才使用 .astype()方法:

So you need first explicitely round them to integers, and only then use the.astype() method:

df['A'] = pd.to_numeric(df['A'].round(), errors='coerce').astype('Int64')


测试:

print(df)
      timestamp     A       B  C
0  1.588758e+09  9088  0.1648  b
1  1.588758e+09  9136  0.1649  a
2  1.588758e+09   NaN           
3  1.588758e+09  9102  5.3379  a

这篇关于将浮点数转换为具有数字和nan的列的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 15:36