【问题标题】:How to set the 'category' data type for a pyarrow Table column?如何为 pyarrow Table 列设置“类别”数据类型?
【发布时间】:2020-09-10 13:53:27
【问题描述】:

我知道使用to_parquet 在镶木地板文件中编写熊猫DataFrame 时可以保留category 类型。

一开始,就我而言,我已经有一个 pyarrow Table。 我可以将其中一列设置为category 类型吗? 如果是,如何? (我一直无法在 Google 和 pyarrow 文档上找到提示)

感谢您的帮助! 最好的,

【问题讨论】:

    标签: python parquet pyarrow


    【解决方案1】:

    在pyarrow中,分类类型被称为“字典类型”。可以使用dictionary_encode() 方法将 pyarrow 数组转换为这样的类型:

    >>> import pyarrow as pa
    >>> table = pa.table({'a': ['A', 'B', 'A']})
    >>> table.schema
    a: string
    
    >>> table.column('a')
    <pyarrow.lib.ChunkedArray object at 0x7f1f94fb9938>
    [
      [
        "A",
        "B",
        "A"
      ]
    ]
    
    >>> table.column('a').dictionary_encode()
    <pyarrow.lib.ChunkedArray object at 0x7f1f94fb9b48>
    [
    
      -- dictionary:
        [
          "A",
          "B"
        ]
      -- indices:
        [
          0,
          1,
          0
        ]
    ]
    

    然后用这个新编码的列改变表有点复杂,但可以这样做:

    >>> table2 = table.set_column(0, "a", table.column('a').dictionary_encode())
    >>> table2.schema
    a: dictionary<values=string, indices=int32, ordered=0>
    
    

    【讨论】:

    • 非常感谢乔里斯!从 pyarrow 数组创建表格时有没有办法做到这一点?
    • pa.table({'a': pa.array(['A', 'B', 'A'], pa.string()).dictionary_encode()})
    猜你喜欢
    • 2020-11-24
    • 2021-05-19
    • 1970-01-01
    • 2016-02-19
    • 2021-05-08
    • 2020-12-12
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多