现在,此程序从csv读取数据,每天对值求和,然后计算累积值。在下一部分中,我希望它将数据保存到新的csv文件中。
import csv
from collections import defaultdict, OrderedDict
def convert(data):
try:
return int(data)
except ValueError:
return 0
with open('Montdata1.csv', 'r') as file1:
read_file = csv.reader(file1, delimiter=';')
delheader = next(read_file)
data = defaultdict(int)
for line in read_file:
valuedata = max(0, sum([convert(i) for i in line[1:5]]))
data[line[0].split()[0]] += valuedata
for key in OrderedDict(sorted(data.items())):
print('{} {}'.format(key, data[key]))
print("")
previous_values = []
for key, value in OrderedDict(sorted(data.items())).items():
print('{} {}'.format(key, value + sum(previous_values)))
previous_values.append(value)
应该在该列中是日期,在第二个中是值。所以会是这样的: https://kotlinexpertise.com/kotlin-coroutines-concurrency/
我尝试了以下代码,但没有执行任何操作:
with open('Datasave.csv', 'w', newline='') as csvfile:
spamreader = csv.reader(csvfile, delimeter= ' ')
for row in spamreader:
print(', '.join(row))
希望获得帮助
数据文件为csv:Example picture
pastebin https://files.fm/u/2vjppmgv
答案 0 :(得分:1)
如果您只想使用原始代码并写入csv文件,则可以在下面查看我的操作方式:
with open('Datasave.csv', 'w') as df:
writer = csv.writer(df, delimiter=';', lineterminator='\n')
for item in data:
writer.writerow([item] + [data[item]])
与大熊猫一起
#!/bin/python
import pandas as pd
df = pd.read_csv('data.csv', sep=';')
df['Sum'] = df[df.columns[2:]].sum(axis=1)
new_df = df.groupby('Time').sum()
new_df['Sum'].to_frame().to_csv('new_data.csv', sep=';')
输出:
Time;Sum
1.1.2016;351087.0
2.1.2016;-2453.0
3.1.2016;0.0
使用标准库:
import csv
dates={}
with open('data.csv', 'r') as df:
df.readline()
f = csv.reader(df, delimiter=';')
for line in f:
if line[0] not in dates:
dates[line[0]] = sum(map(int, line[2:]))
else:
dates[line[0]] += sum(map(int, line[2:]))
with open('new_data.csv', 'w') as df:
writer = csv.writer(df, delimiter=';', lineterminator='\n')
for date in dates:
writer.writerow([date] + [dates[date]])
输出:
Time;Sum
1.1.2016;351087.0
2.1.2016;-2453.0
3.1.2016;0.0