保存pd.DataFrame时如何强制镶木地板dtypes?

时间:2018-05-01 00:46:00

标签: python pandas parquet dask pyarrow

是否有办法强制镶木地板文件将pd.DataFrame列编码为给定类型,即使该列的所有值都为空?镶木地板在其架构中自动指定“null”的事实阻止我将多个文件加载到单个dask.dataframe中。

尝试使用df.column_name = df.column_name.astype(sometype)转换pandas列无效。

为什么我要问这个

我想将多个镶木地板文件加载到一个dask.dataframe中。所有文件均使用pd.DataFramedf.to_parquet(filename)的多个实例生成。所有数据帧都具有相同的列,但对于某些列,给定列可能只包含空值。尝试将所有文​​件加载到dask.dataframe时(使用df = dd.read_parquet('*.parquet'),我收到以下错误:

Schema in filename.parquet was different.
id: int64
text: string
[...]
some_column: double

vs

id: int64
text: string
[...]
some_column: null

重现我的问题的步骤

import pandas as pd
import dask.dataframe as dd
a = pd.DataFrame(['1', '1'], columns=('value',))
b = pd.DataFrame([None, None], columns=('value',))
a.to_parquet('a.parquet')
b.to_parquet('b.parquet')
df = dd.read_parquet('*.parquet')  # Reads a and b

这给了我以下内容:

ValueError: Schema in path/to/b.parquet was different. 
value: null
__index_level_0__: int64
metadata
--------
{b'pandas': b'{"index_columns": ["__index_level_0__"], "column_indexes": [{"na'
            b'me": null, "field_name": null, "pandas_type": "unicode", "numpy_'
            b'type": "object", "metadata": {"encoding": "UTF-8"}}], "columns":'
            b' [{"name": "value", "field_name": "value", "pandas_type": "empty'
            b'", "numpy_type": "object", "metadata": null}, {"name": null, "fi'
            b'eld_name": "__index_level_0__", "pandas_type": "int64", "numpy_t'
            b'ype": "int64", "metadata": null}], "pandas_version": "0.22.0"}'}

vs

value: string
__index_level_0__: int64
metadata
--------
{b'pandas': b'{"index_columns": ["__index_level_0__"], "column_indexes": [{"na'
            b'me": null, "field_name": null, "pandas_type": "unicode", "numpy_'
            b'type": "object", "metadata": {"encoding": "UTF-8"}}], "columns":'
            b' [{"name": "value", "field_name": "value", "pandas_type": "unico'
            b'de", "numpy_type": "object", "metadata": null}, {"name": null, "'
            b'field_name": "__index_level_0__", "pandas_type": "int64", "numpy'
            b'_type": "int64", "metadata": null}], "pandas_version": "0.22.0"}'}

请注意,在一个案例中我们有"pandas_type": "unicode",另一个案例中我们有"pandas_type": "empty"

未向我提供解决方案的相关问题

1 个答案:

答案 0 :(得分:3)

如果您改为使用fastparquet,则可以实现想要的聊天

import pandas as pd
import dask.dataframe as dd
a = pd.DataFrame(['1', '1'], columns=('value',))
b = pd.DataFrame([None, None], columns=('value',))
a.to_parquet('a.parquet', object_encoding='int', engine='fastparquet')
b.to_parquet('b.parquet', object_encoding='int', engine='fastparquet')

dd.read_parquet('*.parquet').compute()

给出

   value
0    1.0
1    1.0
0    NaN
1    NaN