当使用tempfile.TemporaryFile
作为将pandas DF写入csv(to_csv
)的中间层时,一些行将从DF的末尾自动删除。
删除的行数取决于DF的长度和宽度,这似乎是不可预测的。在
实际上,如果DF足够短,所有行都会被删除,结果是一个空文件(没有行写入磁盘)。在
证据表明这是Pandas中的一个bug,但有可能我在纯Python代码中有一个错误。在
参见下面的代码和结果(python3.5,pandas 0.20
import shutil
from io import TextIOWrapper, BufferedWriter
from tempfile import TemporaryFile
import pandas as pd
def pd_bug(size, rep_str):
out_path = "bug_{}_{}".format(rep_str, size)
diags = {"str": [rep_str] * size, "num": [i for i in range(size)]}
df = pd.DataFrame(diags)
with TemporaryFile() as f, BufferedWriter(f) as bw, TextIOWrapper(bw) as iow:
df.to_csv(iow, index=False)
with open(out_path, "w+b") as t:
f.seek(0)
shutil.copyfileobj(f, t)
结果:
^{pr2}$这似乎只在使用类似文件的对象时发生;使用标准
df.to_csv("/a/path/ok")
工作正常——不删除任何行
目前没有回答
相关问题 更多 >
编程相关推荐