如何将任意元数据分配给 pyarrow.Table / Parquet 列

d.a*_*rcy 7 python gis pandas parquet pyarrow

用例

我正在使用 Apache Parquet 文件作为我在 Python 中使用 GeoPandas 处理大型空间数据的快速 IO 格式。我将要素几何存储为 WKB,并希望将坐标参考系统 (CRS) 记录为与 WKB 数据关联的元数据。

代码问题

我正在尝试将任意元数据分配给一个pyarrow.Field对象。

我试过的

假设tablepyarrow.Tabledf, a的实例化pandas.DataFrame

df = pd.DataFrame({
        'foo' : [1, 3, 2],
        'bar' : [6, 4, 5]
        })

table = pa.Table.from_pandas(df)
Run Code Online (Sandbox Code Playgroud)

根据pyarrow文档,列元数据包含在field属于schema( source ) 的 a 中,并且可选的元数据可以添加到field( source ) 中。

如果我尝试为该metadata属性赋值,则会引发错误:

>>> table.schema.field_by_name('foo').metadata = {'crs' : '4283'}
AttributeError: attribute 'metadata' of 'pyarrow.lib.Field' objects is not writable

>>> table.column(0).field.metadata = {'crs' : '4283'}
AttributeError: attribute 'metadata' of 'pyarrow.lib.Field' objects is not writable
Run Code Online (Sandbox Code Playgroud)

如果我尝试将一个字段(通过方法关联的元数据add_metadata)分配给一个字段,它会返回一个错误:

>>> table.schema.field_by_name('foo') = (
           table.schema.field_by_name('foo').add_metadata({'crs' : '4283'})
           )
SyntaxError: can't assign to function call

>>> table.column(0).field = table.column(0).field.add_metadata({'crs' : '4283'})
AttributeError: attribute 'field' of 'pyarrow.lib.Column' objects is not writable
Run Code Online (Sandbox Code Playgroud)

我什至尝试将元数据分配给一个pandas.Series对象,例如

df['foo']._metadata.append({'crs' : '4283'})
Run Code Online (Sandbox Code Playgroud)

但是当在对象的属性上调用pandas_metadata( docs ) 方法时,这不会在元数据中返回。schematable

研究

在 stackoverflow 上,这个问题仍然没有答案,这个相关的问题涉及 Scala,而不是 Python 和pyarrow. 在其他地方,我看到了与pyarrow.Field对象关联的元数据,但只能通过从头开始实例化pyarrow.Fieldpyarrow.Table对象。

聚苯乙烯

这是我第一次在 stackoverflow 上发帖,所以提前感谢并为任何错误道歉。

tho*_*mas 6

Arrow 中的“一切”都是不可变的,因此正如您所经历的,您不能简单地修改任何字段或模式的元数据。执行此操作的唯一方法是使用添加的元数据创建一个“新”表。我将new放在引号之间,因为这可以在不实际复制表格的情况下完成,因为在幕后这只是移动指针。下面是一些代码,展示了如何在 Arrow 元数据中存储任意字典(只要它们是 json 可序列化的)以及如何检索它们:

def set_metadata(tbl, col_meta={}, tbl_meta={}):
    """Store table- and column-level metadata as json-encoded byte strings.

    Table-level metadata is stored in the table's schema.
    Column-level metadata is stored in the table columns' fields.

    To update the metadata, first new fields are created for all columns.
    Next a schema is created using the new fields and updated table metadata.
    Finally a new table is created by replacing the old one's schema, but
    without copying any data.

    Args:
        tbl (pyarrow.Table): The table to store metadata in
        col_meta: A json-serializable dictionary with column metadata in the form
            {
                'column_1': {'some': 'data', 'value': 1},
                'column_2': {'more': 'stuff', 'values': [1,2,3]}
            }
        tbl_meta: A json-serializable dictionary with table-level metadata.
    """
    # Create updated column fields with new metadata
    if col_meta or tbl_meta:
        fields = []
        for col in tbl.itercolumns():
            if col.name in col_meta:
                # Get updated column metadata
                metadata = col.field.metadata or {}
                for k, v in col_meta[col.name].items():
                    metadata[k] = json.dumps(v).encode('utf-8')
                # Update field with updated metadata
                fields.append(col.field.add_metadata(metadata))
            else:
                fields.append(col.field)

        # Get updated table metadata
        tbl_metadata = tbl.schema.metadata
        for k, v in tbl_meta.items():
            tbl_metadata[k] = json.dumps(v).encode('utf-8')

        # Create new schema with updated field metadata and updated table metadata
        schema = pa.schema(fields, metadata=tbl_metadata)

        # With updated schema build new table (shouldn't copy data)
        # tbl = pa.Table.from_batches(tbl.to_batches(), schema)
        tbl = pa.Table.from_arrays(list(tbl.itercolumns()), schema=schema)

    return tbl


def decode_metadata(metadata):
    """Arrow stores metadata keys and values as bytes.
    We store "arbitrary" data as json-encoded strings (utf-8),
    which are here decoded into normal dict.
    """
    if not metadata:
        # None or {} are not decoded
        return metadata

    decoded = {}
    for k, v in metadata.items():
        key = k.decode('utf-8')
        val = json.loads(v.decode('utf-8'))
        decoded[key] = val
    return decoded


def table_metadata(tbl):
    """Get table metadata as dict."""
    return decode_metadata(tbl.schema.metadata)


def column_metadata(tbl):
    """Get column metadata as dict."""
    return {col.name: decode_metadata(col.field.metadata) for col in tbl.itercolumns()}


def get_metadata(tbl):
    """Get column and table metadata as dicts."""
    return column_metadata(tbl), table_metadata(tbl)
Run Code Online (Sandbox Code Playgroud)

简而言之,您使用添加的元数据创建新字段,将字段聚合到新架构中,然后根据现有表和新架构创建新表。这一切都有点啰嗦。理想情况下,pyarrow 将具有方便的函数,可以用更少的代码行来完成此操作,但最后我检查这是执行此操作的唯一方法。

唯一的复杂之处是元数据在 Arrow 中以字节形式存储,因此在上面的代码中,我将元数据存储为 json 可序列化字典,并以 utf-8 进行编码。