亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

PyArrow:使用嵌套類型在鑲木地板中存儲字典列表

PyArrow:使用嵌套類型在鑲木地板中存儲字典列表

jeck貓 2021-11-16 09:58:50
我想使用 PyArrow 將以下 Pandas 數據框存儲在鑲木地板文件中:import pandas as pddf = pd.DataFrame({'field': [[{}, {}]]})field列的類型是字典列表:      field0  [{}, {}]我首先定義相應的 PyArrow 架構:import pyarrow as paschema = pa.schema([pa.field('field', pa.list_(pa.struct([])))])然后我使用from_pandas():table = pa.Table.from_pandas(df, schema=schema, preserve_index=False)這將引發以下異常:Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "table.pxi", line 930, in pyarrow.lib.Table.from_pandas  File "/anaconda3/lib/python3.6/site-packages/pyarrow/pandas_compat.py", line 371, in dataframe_to_arrays    convert_types)]  File "/anaconda3/lib/python3.6/site-packages/pyarrow/pandas_compat.py", line 370, in <listcomp>    for c, t in zip(columns_to_convert,  File "/anaconda3/lib/python3.6/site-packages/pyarrow/pandas_compat.py", line 366, in convert_column    return pa.array(col, from_pandas=True, type=ty)  File "array.pxi", line 177, in pyarrow.lib.array  File "error.pxi", line 77, in pyarrow.lib.check_status  File "error.pxi", line 87, in pyarrow.lib.check_statuspyarrow.lib.ArrowTypeError: Unknown list item type: struct<>我做錯了什么還是 PyArrow 不支持?我使用 pyarrow 0.9.0、pandas 23.4、python 3.6。
查看完整描述

3 回答

?
拉莫斯之舞

TA貢獻1820條經驗 獲得超10個贊

根據這個 Jira 問題,在 2.0.0 版中實現了混合結構和列表嵌套級別的嵌套 Parquet 數據的讀取和寫入。


以下示例通過執行往返來演示實現的功能:pandas 數據框 -> parquet 文件 -> pandas 數據框。使用的 PyArrow 版本是 3.0.0。


最初的熊貓數據框有一個字典類型列表的字段和一個條目:


                  field

0  [{'a': 1}, {'a': 2}]

示例代碼:


import pandas as pd

import pyarrow as pa

import pyarrow.parquet


df = pd.DataFrame({'field': [[{'a': 1}, {'a': 2}]]})

schema = pa.schema(

    [pa.field('field', pa.list_(pa.struct([('a', pa.int64())])))])

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

pyarrow.parquet.write_table(table_write, 'test.parquet')

table_read = pyarrow.parquet.read_table('test.parquet')

table_read.to_pandas()

輸出數據幀與輸入數據幀相同,因為它應該是:


                  field

0  [{'a': 1}, {'a': 2}]


查看完整回答
反對 回復 2021-11-16
?
千巷貓影

TA貢獻1829條經驗 獲得超7個贊

這是重現此錯誤的片段:


#!/usr/bin/env python3

import pandas as pd  # type: ignore



def main():

    """Main function"""

    df = pd.DataFrame()

    df["nested"] = [[dict()] for i in range(10)]


    df.to_feather("test.feather")

    print("Success once")

    df = pd.read_feather("test.feather")

    df.to_feather("test.feather")



if __name__ == "__main__":

    main()

請注意,從熊貓到羽毛,沒有任何中斷,但是一旦從羽毛加載數據幀并嘗試寫回它,它就會中斷。


要解決這個問題,只需更新到 pyarrow 2.0.0:


pip3 install pyarrow==2.0.0

截至 2020 年 11 月 16 日可用的 pyarrow 版本:


0.9.0, 0.10.0, 0.11.0, 0.11.1, 0.12.0, 0.12.1, 0.13.0, 0.14.0, 0.15.1, 0.16.0, 0.17.0, 0.17.1., 10 0、1.0.1、2.0.0


查看完整回答
反對 回復 2021-11-16
?
翻翻過去那場雪

TA貢獻2065條經驗 獲得超14個贊

我已經能夠將列中有數組的 Pandas 數據幀保存為鑲木地板,并通過將對象的數據幀 dtypes 轉換為 str 將它們從鑲木地板讀回數據幀。


def mapTypes(x):

    return {'object': 'str', 'int64': 'int64', 'float64': 'float64', 'bool': 'bool',

            'datetime64[ns, ' + timezone + ']': 'datetime64[ns, ' + timezone + ']'}.get(x,"str")  # string is     default if type not mapped


table_names = [x for x in df.columns]

table_types = [mapTypes(x.name) for x in df.dtypes]

parquet_table = dict(zip(table_names, table_types))    

df_pq = df.astype(parquet_table)

import awswrangler as wr

wr.s3.to_parquet(df=df_pq,path=path,dataset=True,database='test',mode='overwrite',table=table.lower(),partition_cols=['realmid'],sanitize_columns=True)


下圖顯示了使用 AWS datawrangler 庫從存儲在 s3 中的鑲木地板文件讀取到數據幀,我也使用 pyarrow 完成了此操作 

http://img1.sycdn.imooc.com//6193108200016dbd08260349.jpg

查看完整回答
反對 回復 2021-11-16
  • 3 回答
  • 0 關注
  • 440 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號