python - 通过 pandas vs pyarrow 转换模式

标签 python pandas dataframe pyarrow

我在 pandas 中有一个数据框,我想使用 pyarrow 将它写成 Parquet 。

我还需要能够指定列类型。如果我通过 pandas 更改类型,我不会出错;但是当我通过 pyarrow 更改它时,出现错误。查看示例:

给定

import pandas as pd
import pyarrow as pa

data = {"col": [86002575]}
df = pd.DataFrame(data)

通过 Pandas

df = df.astype({"col": "float32"})

table = pa.Table.from_pandas(df)

没有错误

通过 PyArrow

schema = pa.Schema.from_pandas(df)
i = schema.get_field_index("col")
schema = schema.set(i, pa.field("col", pa.float32()))

table = pa.Table.from_pandas(df, schema=schema)

获取错误:

pyarrow.lib.ArrowInvalid: ('Integer value 86002575 not in range: -16777216 to 16777216', 'Conversion failed for column col with type int64')

我什至不认识那个范围。是否在两者之间转换时尝试做一些中间转换?

最佳答案

从一种类型转换为另一种类型时,arrow 比 pandas 严格得多。

在您的情况下,您正在从 int64 转换为 float32。因为它们限制了整数在 float 中的精确表示,所以箭头限制了您可以转换为 16777216 的范围。超过该限制,浮点精度会变差,如果您要将浮点值转换回 int,则不保证具有相同的值。

不过您可以轻松地忽略这些检查:

schema_float32 = pa.schema([pa.field("col", pa.float32())])
table = pa.Table.from_pandas(df, schema=schema_float32, safe=False)

编辑:

它没有在箭头中明确记录。这是常见的软件工程知识。

In wikipedia:

Any integer with absolute value less than 2^24 can be exactly represented in the single precision format, and any integer with absolute value less than 2^53 can be exactly represented in the double precision format. Furthermore, a wide range of powers of 2 times such a number can be represented. These properties are sometimes used for purely integer data, to get 53-bit integers on platforms that have double precision floats but only 32-bit integers.

2^24 = 16777216

箭头中没有很好地记录。你可以看看code

关于python - 通过 pandas vs pyarrow 转换模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66267995/

相关文章:

python - 如何将参数传递给 win32com 事件处理程序

python - 在哪里使用pyc文件

带有if语句的python数据框 bool 值

python - 我可以在删除每个组中的第一个和最后一个条目的同时使用 Pandas group by 吗?

python - 如何使用 iterrows 和 iteritems 更快地运行 pandas for 循环

python - 选择用于复制 Pandas DataFrame 的列

python:如果我在关闭文件之前退出,打开的文件会发生什么?

python - Sierpinski 的三角形 Pygame 递归

python - 如何仅选择值超过阈值的行?

python - 有没有办法从 Flask 用户输入动态查询 postgres 数据库?