简体   繁体   English

将 Pandas Dataframe 中的一行数据输入到 csv 文件中的下一个空行

[英]Enter row of data from Pandas Dataframe to next empty row in a csv file

I would like to write the values coming from a single row dataframe to the next available empty row in a csv file.我想将来自单行数据帧的值写入 csv 文件中的下一个可用空行。


df8 = pd.DataFrame([Accuracy])
df8.to_csv('accuracies.csv',header=False)

As it stands at the moment it always rewrites the first row on the csv.就目前而言,它总是重写 csv 上的第一行。

eg the accuracy list contains 10 values which will change every time I run an experiment.例如,准确度列表包含 10 个值,每次我运行实验时这些值都会改变。 At the moment every time I run the experiment the values overwrite the first row of data in the csv.目前,每次我运行实验时,这些值都会覆盖 csv 中的第一行数据。

在此处输入图片说明

What I try to achieve is the values to be written in the next empty row below.我试图实现的是要在下面的下一个空行中写入的值。 在此处输入图片说明

Try this:尝试这个:

df8 = pd.DataFrame([Accuracy])
df8.to_csv('accuracies.csv',header=False, mode='a')

When writing to a text (or csv) file with python you must select a mode.使用 python 写入文本(或 csv)文件时,您必须选择一种模式。 Like in C you can open a file in r, w and a modes.就像在 C 中一样,您可以在 r、w 和 a 模式下打开文件。

  • r opens for reading and writing (no truncating, file pointer at the beginning) r 以读写方式打开(不截断,文件指针在开头)
  • w opens for writing (and thus truncates the file) and reading w 打开以进行写入(从而截断文件)和读取
  • a opens for appending (writing without truncating, only at the end of the file, and the file pointer is at the end of the file) and reading a 打开追加(写入不截断,只在文件末尾,文件指针在文件末尾)和读取

You can add the mode to your to_csv method as written in the to_csv documentation:您可以将模式添加到 to_csv 方法中,如 to_csv 文档中所述:

mode : str
Python write mode, default ‘w’.

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM