我在 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)
编辑:
它没有在箭头中明确记录。这是常见的软件工程知识。
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/