[英]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?
但结果将替换 ori 现有数据,我该如何更改它? 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.另一种选择可能是:最后将所有内容保存到 xlsx 中(如果有大量数据,最好从 CSV 加载数据)并将 dataframe1 保存在第一张纸中,并在第二张纸上进行分析。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.