将DataFrame转换为列表时,浮点精度受到影响 [英] Floating point precision affected when converting DataFrame to list

查看:739
本文介绍了将DataFrame转换为列表时,浮点精度受到影响的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我试图通过使用row.values.tolist()(从CSV文件读取row)将浮点型DataFrame转换为列表(列表).它的工作还可以,尽管对于一些值而言,精度会受到影响,因此,例如,它输出的是32.336999999999996.

So I'm trying to convert a float DataFrame to a list (of list) by using row.values.tolist() (row was read from a CSV file). It does the job pretty okay though for a few values the precision is being affected, so, for instance, instead of 32.337 it's outputting 32.336999999999996.

由于tolist()产生了 list列表,并且我需要使用 lists ,所以我决定改用list(row.values.flatten()),但是它几乎引入了精度问题列表中的 any 值,这只会使其变得更糟.

Since tolist() yields a list of list and I need to work with lists, I decided to switch to list(row.values.flatten()), but it introduces precision issues for almost any value in the list, which just makes it worst.

大约3年前,我发现了有关此问题的关于Github的讨论,但我找不到最新的东西,也不知道该如何克服.

I found a discussion on Github about this issue, from almost 3 years ago, but I can't find anything else up to date and I have no idea how to overcome this.

我尝试使用pd.set_option('display.precision',4),因为对于大多数值,我最多需要四个有效数字,但这也不起作用(假设我正确使用了它).

I tried using pd.set_option('display.precision',4) since for most values I need a maximum of four significant digits, but this isn't working either (assuming I'm using it right).

有什么解决方法吗?

推荐答案

Eventhough,根据基值,您可能仍然会遇到精度问题. 您仍然可以使用round指定希望的小数位数.

Eventhough, you might still have a problem with precision depending on the base values. You can still use round to specify the amount of decimal you wish to have.

df = pd.DataFrame([(.2132481, .399452), (.012311, .13267), (.613216, .01233), (.213211, .181235)])
df.values.round(3).tolist()

>> [[0.213, 0.399], [0.012, 0.133], [0.613, 0.012], [0.213, 0.181]]

.round(3)中的3保留三位小数.

这篇关于将DataFrame转换为列表时,浮点精度受到影响的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆