Pandas to_csv删除行(写入文件类对象时)

2024-04-26 20:44:49 发布

您现在位置:Python中文网/ 问答频道 /正文

当使用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")工作正常——不删除任何行


Tags: csvtopathimportpandasdfsizeas