将 Pandas DataFrame 与 In-Memory Feather 相互转换
Convert Pandas DataFrame to & from In-Memory Feather
使用 IO tools in pandas 可以将 DataFrame
转换为内存中的羽化缓冲区:
import pandas as pd
from io import BytesIO
df = pd.DataFrame({'a': [1,2], 'b': [3.0,4.0]})
buf = BytesIO()
df.to_feather(buf)
但是,使用相同的缓冲区转换回 DataFrame
pd.read_feather(buf)
结果出错:
ArrowInvalid: Not a feather file
如何将 DataFrame 转换为内存中的羽毛表示,并相应地返回 DataFrame?
提前感谢您的考虑和回复。
使用 pandas==0.25.2
这可以通过以下方式完成:
import pandas
import io
df = pandas.DataFrame(data={'a': [1, 2], 'b': [3.0, 4.0]})
buf = io.BytesIO()
df.to_feather(buf)
output = pandas.read_feather(buf)
然后调用 output.head(2)
returns:
a b
0 1 3.0
1 2 4.0
如果您有一个包含多个索引的 DataFrame
,您可能会看到类似
的错误
ValueError: feather does not support serializing for the index; you can .reset_index()to make the index into column(s)
在这种情况下,您需要在 to_feather
之前调用 .reset_index()
,并在 read_feather
之后调用 .set_index([...])
我想补充的最后一件事是,如果您正在使用 BytesIO
做某事,您需要在写入羽化字节后返回到 0。例如:
buffer = io.BytesIO()
df.reset_index(drop=False).to_feather(buffer)
buffer.seek(0)
s3_client.put_object(Body=buffer, Bucket='bucket', Key='file')
使用 IO tools in pandas 可以将 DataFrame
转换为内存中的羽化缓冲区:
import pandas as pd
from io import BytesIO
df = pd.DataFrame({'a': [1,2], 'b': [3.0,4.0]})
buf = BytesIO()
df.to_feather(buf)
但是,使用相同的缓冲区转换回 DataFrame
pd.read_feather(buf)
结果出错:
ArrowInvalid: Not a feather file
如何将 DataFrame 转换为内存中的羽毛表示,并相应地返回 DataFrame?
提前感谢您的考虑和回复。
使用 pandas==0.25.2
这可以通过以下方式完成:
import pandas
import io
df = pandas.DataFrame(data={'a': [1, 2], 'b': [3.0, 4.0]})
buf = io.BytesIO()
df.to_feather(buf)
output = pandas.read_feather(buf)
然后调用 output.head(2)
returns:
a b
0 1 3.0
1 2 4.0
如果您有一个包含多个索引的 DataFrame
,您可能会看到类似
ValueError: feather does not support serializing for the index; you can .reset_index()to make the index into column(s)
在这种情况下,您需要在 to_feather
之前调用 .reset_index()
,并在 read_feather
.set_index([...])
我想补充的最后一件事是,如果您正在使用 BytesIO
做某事,您需要在写入羽化字节后返回到 0。例如:
buffer = io.BytesIO()
df.reset_index(drop=False).to_feather(buffer)
buffer.seek(0)
s3_client.put_object(Body=buffer, Bucket='bucket', Key='file')