首页 > 解决方案 > Pandas df.to_csv() 保存我的文件的旧版本,而不是我修改过的文件

问题描述

我有一个数据框,我正在替换 NaN 和零值。在 jupyter notebook 中看起来一切都很好,但是当我使用 df.to_csv() 时,它基本上创建了原始数据帧的副本,其中包含所有零和 NaN 值。

我已经尝试了所有组合和方法来编写它应该去的路径。

df = pd.read_csv(r"C:\Users\Eddie\Downloads\pandas\Deformation.txt", error_bad_lines=False)
df.dropna(axis=1, how="all", inplace=True)

suffixes = ["_A", "_B"]

for suffix in suffixes:
    # Välj ut alla DIG*_*-kolumner och spara i en lista
    dig_cols = [col for col in df.columns if (col.replace(" 
    ","").startswith("DI") and col.endswith(suffix))]

    # Säkerställ att alla DIG*_*-kolumner är decimaltal
    for col in dig_cols:
        df[col] = df[col].astype(float)
        df[col].replace(0, np.nan, inplace=True)
        df[col].fillna(method="ffill", inplace=True)

path = r"C:\Users\Eddie\Downloads\pandas"
df.to_csv(os.path.join(path, "Deformation_new.txt"))

标签: pythonpython-3.xpandasdataframeexport-to-csv

解决方案


您应该尝试如下绝对路径,但是当您使用to_csv 它时,它意味着comma分隔值,因此,您可能希望通过comma分隔或tab分隔导出值,您可以在使用DataFrame.to_csv方法时定义这些值。

对于逗号分隔值:

df.to_csv(r"C:\Users\Eddie\Downloads\pandas\Deformation_new.txt", sep=",", index=False)

对于制表符分隔值:

df.to_csv(r"C:\Users\Eddie\Downloads\pandas\Deformation_new.txt", sep="\t", index=False)

推荐阅读