通过 pandas 与 pyarrow 转换模式

Converting schemas via pandas vs pyarrow

我在 pandas 中有一个数据框,我想使用 pyarrow 将其写成镶木地板。

我还需要能够指定列类型。如果我通过 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')

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

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

在您的情况下,您正在从 int64 转换为 float32。因为它们限制了整数在浮点数中的精确表示,所以箭头限制了您可以转换为 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