pandas pd.read_table 支持 io.BytesIO 和 StringIO 吗?
pandas does pd.read_table support io.BytesIO and StringIO?
我有一个 io.BytesIO
object、iostream
,这是一个从磁盘读取的 be2 文件,我打算将列 headers 附加到 table/iostream
,
f = io.BytesIO()
f.write(b'A,B,C,D\n')
f.write(iostream.getvalue())
pd.read_table(f, sep=',', index_col=False, error_bad_lines=False, encoding='utf-8', dtype=type_map)
但是它给了我一个错误,
pandas.errors.EmptyDataError: No columns to parse from file
我想知道如何解决这个问题。
也试过
f = io.StringIO()
f.write('A,B,C,D\n')
f.write(iostream.getvalue().decode())
pd.read_table(f, sep=',', index_col=False, error_bad_lines=False, encoding='utf-8', dtype=type_map)
遇到错误
pandas.errors.ParserError: Error tokenizing data. C error: Calling read(nbytes) on source failed. Try engine='python'.
我成功重现了你的错误。您在第一次尝试时遇到的问题是,您在调用 'pd.read_table' 时位于流 'f' 的末尾,因为您刚刚编写了所有内容。 'pd.read_table' 在内部调用 read(),它从您当前的位置开始读取。所以它 returns 是一个空字符串。这是错误的原因:
pandas.errors.EmptyDataError: No columns to parse from file
解决方法很简单。您只需使用 'seek' 再次移至流的开头。此代码对我有用:
f = io.BytesIO()
f.write(b'A,B,C,D\n')
f.write(iostream.getvalue())
f.seek(0)
pd.read_table(f, sep=',', index_col=False, error_bad_lines=False, encoding='utf-8')
我有一个 io.BytesIO
object、iostream
,这是一个从磁盘读取的 be2 文件,我打算将列 headers 附加到 table/iostream
,
f = io.BytesIO()
f.write(b'A,B,C,D\n')
f.write(iostream.getvalue())
pd.read_table(f, sep=',', index_col=False, error_bad_lines=False, encoding='utf-8', dtype=type_map)
但是它给了我一个错误,
pandas.errors.EmptyDataError: No columns to parse from file
我想知道如何解决这个问题。
也试过
f = io.StringIO()
f.write('A,B,C,D\n')
f.write(iostream.getvalue().decode())
pd.read_table(f, sep=',', index_col=False, error_bad_lines=False, encoding='utf-8', dtype=type_map)
遇到错误
pandas.errors.ParserError: Error tokenizing data. C error: Calling read(nbytes) on source failed. Try engine='python'.
我成功重现了你的错误。您在第一次尝试时遇到的问题是,您在调用 'pd.read_table' 时位于流 'f' 的末尾,因为您刚刚编写了所有内容。 'pd.read_table' 在内部调用 read(),它从您当前的位置开始读取。所以它 returns 是一个空字符串。这是错误的原因:
pandas.errors.EmptyDataError: No columns to parse from file
解决方法很简单。您只需使用 'seek' 再次移至流的开头。此代码对我有用:
f = io.BytesIO()
f.write(b'A,B,C,D\n')
f.write(iostream.getvalue())
f.seek(0)
pd.read_table(f, sep=',', index_col=False, error_bad_lines=False, encoding='utf-8')