Ben*_*n G 6 python r list pandas feather
我正在使用 R 和 Python,我想将我的一个 Pandas DataFrames 写成一个羽毛,这样我就可以在 R 中更轻松地使用它。但是,当我尝试将它写成一个羽毛时,我收到以下错误:
ArrowInvalid: trying to convert NumPy type float64 but got float32
Run Code Online (Sandbox Code Playgroud)
我仔细检查了我的列类型,它们已经浮动 64:
In[1]
df.dtypes
Out[1]
id Object
cluster int64
vector_x float64
vector_y float64
Run Code Online (Sandbox Code Playgroud)
无论使用feather.write_dataframe(df, "path/df.feather")
或 ,我都会遇到相同的错误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
Run Code Online (Sandbox Code Playgroud)
编辑2:
经过多次搜索,问题似乎是我的簇列是由 int64 整数组成的列表类型。所以我想真正的问题是,羽毛格式是否支持列表?
编辑3:
只是为了将其联系起来,feather 不支持嵌套数据类型,例如列表,至少现在不支持。
您的情况的问题是id Object
列。这些是 Python 对象,它们不能以语言中性格式表示。这个羽毛(实际上是底层的 Apache Arrow / pyarrow
)试图猜测id
列的 DataType 。猜测是在它在列中看到的第一个对象上完成的。这些是float64
numpy 标量。后来,你有float32
标量。Arrow 并没有将它们强制为某种类型,而是对类型更加严格并且失败了。
您应该能够通过确保所有列都具有带有df['id'] = df['id'].astype(float)
.
小智 2
- 幸运的是,我在这里找到了我的feather IO错误的原因。
- 我也得到了这个问题的解决方案,pandas.to_feather和read_feather都是基于pyarrow,并且从2019年开始pyarrow已经支持包含列表作为值的列。
解决方案:
pip install pyarrow==latest # my version is 1.0.0 and it work
Run Code Online (Sandbox Code Playgroud)
然后,仍然使用 pd.to_feather("Filename") 和 read_feather。