【问题标题】:Pandas df.to_csv() saves the old version of my file instead of the one i have modifiedPandas df.to_csv() 保存我的文件的旧版本,而不是我修改过的文件
【发布时间】:2019-01-18 19:28:48
【问题描述】:

我有一个要替换 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"))

【问题讨论】:

  • 先尝试使用相对路径:df.to_csv("Deformation_new.txt"),而不是绝对路径。它将在您运行脚本的当前目录中写入 csv。但无论如何,这不应该是问题。在你将 df 写入文件之前,打印它并检查它是否真的被前面的代码修改了。
  • 我们无法启动代码,因为没有minimal reproducible example,但请注意:您不应该在熊猫中使用inplace 参数。它将成为 1.0 中已弃用的参数,并在一年内删除。所以,只是说:不要在你的生产代码上实现它。
  • 感谢您的回答!我试过使用绝对路径。我还尝试在将 df 写入文件之前打印它,然后它看起来不错,这是令人沮丧的部分,没有任何意义。另外,我不知道inplace参数,谢谢!

标签: python python-3.x pandas dataframe export-to-csv


【解决方案1】:

您应该尝试如下绝对路径,但是当您使用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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-18
    • 2019-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-10
    • 2022-01-03
    • 1970-01-01
    相关资源
    最近更新 更多