简体   繁体   中英

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.


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.

eg the accuracy list contains 10 values which will change every time I run an experiment. At the moment every time I run the experiment the values overwrite the first row of data in the 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. Like in C you can open a file in r, w and a modes.

  • r opens for reading and writing (no truncating, file pointer at the beginning)
  • w opens for writing (and thus truncates the file) and reading
  • 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

You can add the mode to your to_csv method as written in the to_csv documentation:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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