我正在把熊猫的数据转换成极地数据,但是皮罗会抛出错误。
我的代码:
import polars as pl
import pandas as pd
if __name__ == "__main__":
with open(r"test.xlsx", "rb") as f:
excelfile = f.read()
excelfile = pd.ExcelFile(excelfile)
sheetnames = excelfile.sheet_names
df = pd.concat(
[
pd.read_excel(
excelfile, sheet_name=x, header=0)
for x in sheetnames
], axis=0)
df_pl = pl.from_pandas(df)
错误:
File "pyarrow\array.pxi", line 312, in pyarrow.lib.array
File "pyarrow\array.pxi", line 83, in pyarrow.lib._ndarray_to_array
File "pyarrow\error.pxi", line 122, in pyarrow.lib.check_status
pyarrow.lib.ArrowTypeError: Expected bytes, got a 'int' object
我试着把熊猫的dataframe dtype
改成str
,问题解决了,但我不想改变dtypes
。是有误,还是我漏掉了什么?
发布于 2022-03-29 21:36:12
编辑: Polars 0.13.42
及更高版本
Polars现在有一个read_excel
函数,可以正确地处理这种情况。现在,read_excel
是将Excel文件读入极坐标的首选方法。
注意:要使用read_excel
,您需要安装xlsx2csv
(可以用pip安装)。
极地:在0.13.42
之前
我可以复制这个结果。这是由于原始Excel文件中包含文本和数字的列造成的。
例如,创建一个新的Excel文件,其中包含一个列,在其中键入数字和文本,保存它,然后在该文件上运行您的代码。我得到以下回溯:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/xxx/.virtualenvs/StackOverflow3.10/lib/python3.10/site-packages/polars/convert.py", line 299, in from_pandas
return DataFrame._from_pandas(df, rechunk=rechunk, nan_to_none=nan_to_none)
File "/home/xxx/.virtualenvs/StackOverflow3.10/lib/python3.10/site-packages/polars/internals/frame.py", line 454, in _from_pandas
pandas_to_pydf(
File "/home/xxx/.virtualenvs/StackOverflow3.10/lib/python3.10/site-packages/polars/internals/construction.py", line 485, in pandas_to_pydf
arrow_dict = {
File "/home/xxx/.virtualenvs/StackOverflow3.10/lib/python3.10/site-packages/polars/internals/construction.py", line 486, in <dictcomp>
str(col): _pandas_series_to_arrow(
File "/home/xxx/.virtualenvs/StackOverflow3.10/lib/python3.10/site-packages/polars/internals/construction.py", line 237, in _pandas_series_to_arrow
return pa.array(values, pa.large_utf8(), from_pandas=nan_to_none)
File "pyarrow/array.pxi", line 312, in pyarrow.lib.array
File "pyarrow/array.pxi", line 83, in pyarrow.lib._ndarray_to_array
File "pyarrow/error.pxi", line 122, in pyarrow.lib.check_status
pyarrow.lib.ArrowTypeError: Expected bytes, got a 'int' object
关于这一问题有几次长时间的讨论,例如:
这个特定的注释可能是相关的,因为您正在连接一个Excel文件中的多个表的解析结果。这可能导致列的dtype冲突:https://github.com/pandas-dev/pandas/issues/21228#issuecomment-419175116。
如何处理这个问题取决于您的数据及其使用,因此我不能推荐一个总括解决方案(即修复源Excel文件,或者将dtype更改为str)。
https://stackoverflow.com/questions/71657556
复制相似问题