首页 > 解决方案 > 尝试将 DataFrame 写入羽毛时出错。羽毛是否支持列表列?

问题描述

我正在使用 R 和 Python,并且我想将我的 pandas DataFrames 之一编写为羽毛,以便我可以在 R 中更轻松地使用它。但是,当我尝试将其编写为羽毛时,我收到以下错误:

ArrowInvalid: trying to convert NumPy type float64 but got float32

我仔细检查了我的列类型,它们已经是浮点数 64:

In[1]
df.dtypes

Out[1]
id         Object
cluster    int64
vector_x   float64
vector_y   float64

无论使用feather.write_dataframe(df, "path/df.feather")or ,我都会遇到相同的错误df.to_feather("path/df.feather")

我在 GitHub 上看到了这个,但不明白它是否相关:https ://issues.apache.org/jira/browse/ARROW-1345和https://github.com/apache/arrow/issues/1430

最后,我可以将其保存为 csv 并更改 R 中的列(或仅在 Python 中进行整个分析),但我希望使用它。

编辑1:

尽管下面有很好的建议,但仍然有同样的问题,所以更新了我尝试过的内容。

df[['vector_x', 'vector_y', 'cluster']] = df[['vector_x', 'vector_y', 'cluster']].astype(float)

df[['doc_id', 'text']] = df[['doc_id', 'text']].astype(str)

df[['doc_vector', 'doc_vectors_2d']] = df[['doc_vector', 'doc_vectors_2d']].astype(list)

df.dtypes

Out[1]:
doc_id           object
text             object
doc_vector       object
cluster          float64
doc_vectors_2d   object
vector_x         float64
vector_y         float64
dtype: object

编辑2:

经过大量搜索,问题似乎在于我的集群列是由 int64 整数组成的列表类型。所以我想真正的问题是,羽毛格式是否支持列表?

编辑3:

简单地说,feather 不支持像列表这样的嵌套数据类型,至少现在还不支持。

标签: pythonrpandaslistfeather

解决方案


您的问题是id Object列。这些是 Python 对象,它们不能以语言中立的格式表示。这个羽毛(实际上是底层的 Apache Arrow / pyarrow)试图猜测id列的 DataType。猜测是在它在列中看到的第一个对象上完成的。这些是float64numpy 标量。后来,你有float32标量。Arrow 没有将它们强制为某种类型,而是对类型更加严格并且失败了。

您应该能够通过确保所有列都具有非对象 dtype 来解决此问题df['id'] = df['id'].astype(float)


推荐阅读