【问题标题】:Assign schema to pa.Table.from_pandas()将模式分配给 pa.Table.from_pandas()
【发布时间】:2018-09-08 23:32:24
【问题描述】:

使用 pyArrow 将 pandas.DF 转换为镶木地板时出现此错误:

ArrowInvalid('Error converting from Python objects to Int64: Got Python object of type str but can only handle these types: integer

为了找出问题所在的列,我在 for 循环中创建了一个新的 df,首先使用第一列,然后为每个循环添加另一列。我意识到错误出现在以 0 开头的 dtype: object 列中,我猜这就是为什么 pyArrow 想要将该列转换为 int 但由于其他值是 UUID 而失败的原因

我试图传递一个架构:(不确定这是否是要走的路)

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

架构在哪里:df.dtypes

【问题讨论】:

  • 也许可以分享df.head()df.info() 的输出,或者提供一个最小的工作示例。

标签: python pandas parquet pyarrow


【解决方案1】:

Carlos 您是否尝试将列转换为https://arrow.apache.org/docs/python/pandas.html 此处列出的 Pandas 类型之一?

你能发布 df.dtypes 的输出吗?

如果更改 pandas 列类型没有帮助,您可以定义一个 pyarrow 模式来传递。

fields = [
    pa.field('id', pa.int64()),
    pa.field('secondaryid', pa.int64()),
    pa.field('date', pa.timestamp('ms')),
]

my_schema = pa.schema(fields)

table = pa.Table.from_pandas(sample_df, schema=my_schema, preserve_index=False)

更多信息在这里:

https://arrow.apache.org/docs/python/data.html https://arrow.apache.org/docs/python/generated/pyarrow.Table.html#pyarrow.Table.from_pandas https://arrow.apache.org/docs/python/generated/pyarrow.schema.html

【讨论】:

  • 将 ID 存储为 int(在当前 pandas 中)可能会在缺少值(转换为具有长 ID 的浮点数时丢失信息)或 ID 变得非常长(20+ 字符)时出现问题
  • 嗨,Alexander,我想将 df dtypes 列保留为对象,因为稍后会进行其他操作和转换。我正在尝试 pa.schema,如果这不起作用,那么我将强制 df dtypes。
  • 在编写 parquet 时,它实际上并不推断模式。我在列中没有,我想将它们转换为 int64,但它在写入时将列转换为浮点,但在 table.schema 中它显示 int64
猜你喜欢
  • 2019-01-14
  • 1970-01-01
  • 1970-01-01
  • 2020-08-16
  • 1970-01-01
  • 2015-05-23
  • 2021-10-02
  • 2021-10-07
  • 1970-01-01
相关资源
最近更新 更多