简体   繁体   中英

How to write back the result to the csv file using pandas without replace the existing data?

I am trying to read the file, then i would like to done the calculation to write back to the same file. But the result will replace the ori existing data, how can i change it? Please help me

import pandas as pd

df = pd.read_csv(r'C:\Users\Asus\Downloads\Number of Employed Persons by Status In Employment, Malaysia.csv')

print(df.to_string())

mean1 = df['Value'].mean()
sum1 = df['Value'].sum()

print ('Mean Value: ' + str(mean1))
print ('Sum of Value: ' + str(sum1))

df = pd.DataFrame([['Mean Value: ' + str(mean1)], ['Sum of Value: ' + str(sum1)]])

df.to_csv(r'C:\Users\Asus\Downloads\Number of Employed Persons by Status In Employment, Malaysia.csv', index=False)

print(df)

Do you want to add the data at the bottom of the file?

Override the data is not the best approach, in my opinion, but this is one solution:

import pandas as pd

df = pd.read_csv('data.csv')

mean1 = df['Value'].mean() 
sum1 = df['Value'].sum()

df.loc[df.index.max() + 1] = ['Mean','Sum']
df.loc[df.index.max() + 1] = [mean1, sum1]

df.to_csv('data.csv', index=False)

Another option could be: Save all into an xlsx at the end (is better load the data from CSV if there is a large of data) and keep the dataframe1 in a first sheet, and the analysis on a second sheet.

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