python - 尝试将 DataFrame 写入 Feather 时出错。 feather 是否支持列表列?

标签 python r pandas list feather

我同时使用 R 和 Python,我想将我的一个 pandas DataFrame 编写为一个 feather,以便我可以在 R 中更轻松地使用它。但是,当我尝试将其编写为 feather 时,我得到以下错误:

ArrowInvalid: trying to convert NumPy type float64 but got float32

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

In[1]
df.dtypes

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

无论使用 feather.write_dataframe(df, "path/df.feather") 还是 df.to_feather("path/df.feather").

我在 GitHub 上看到这个,但不明白它是否相关:https://issues.apache.org/jira/browse/ARROW-1345https://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 整数组成的列表类型。所以我想真正的问题是, Feather 格式是否支持列表?

编辑 3:

顺便提一下,Feather 不支持像列表这样的嵌套数据类型,至少现在不支持。

最佳答案

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

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

关于python - 尝试将 DataFrame 写入 Feather 时出错。 feather 是否支持列表列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54354983/

相关文章:

R 绘制包含序列/列表的函数

r - 当列名等于行值时,结合两个数据框来计算变量

python - 如何使用 Pandas 获取单元格的值并存储到变量中?

python - IO错误 : File not open for writing - Python

python - 如何在 mac 上自定义 tkinter 菜单栏?

python - 如何在python中创建一个每天枚举的循环?

r - 时间序列平滑,避免修改

python 列表迭代

python - Pandas 错误 "***ValueError: Length mismatch: Expected axis has 0 elements, new values have..."

python - 使用 MultiIndex 重新索引 pandas.panel