在此先感谢您的帮助。我是Python的新手(并且通常是编码人员),并且尝试使用以下导入的CSV文件来做几件事。我遇到的问题是捕获(在列表中)从一行到下一行的收入变化,例如,从10/18到11/18的收入变化。理想情况下,我将有一个["month", "change vs previous"]
的最终名单。
这是我现有的代码:
import os
import csv
csvpath = os.path.join("C:/test2", "budget_data.csv")
num_rows=0
total_rev=0
with open(csvpath, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter= ",")
print(csvreader)
csv_header =next(csvreader)
print(f"CSV Header: {csv_header}")
for row in csvreader:
num_rows=num_rows+1
total_rev += int(row[1])
print("")
print("There are "+ str(num_rows) +" months of data!")
print("Total Revenue is "+str(total_rev)+" dollars!")
答案 0 :(得分:0)
您需要添加一个变量来保存上一行的收入。在每个循环结束时进行更新:
import os
import csv
csvpath = os.path.join("C:/test2", "budget_data.csv")
num_rows = 0
total_rev = 0
change_from_previous = []
with open(csvpath, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
print(csvreader)
csv_header = next(csvreader)
print(f"CSV Header: {csv_header}")
previous_revenue = 0
for row in csvreader:
revenue = int(row[1])
num_rows += 1
total_rev += revenue
change_from_previous.append([row[0], revenue - previous_revenue])
previous_revenue = revenue
print("")
print("There are "+ str(num_rows) +" months of data!")
print("Total Revenue is "+str(total_rev)+" dollars!")
print(change_from_previous)
这将显示每月保存的列表并更改:
[['Jan-10', 867884], ['Feb-10', 116771], ['Mar-10', -662642], ['Apr-10', -391430], ['May-10', 379920], ['Jun-10', 212354], ['Jul-10', 510239], ['Aug-10', -428211], ['Sep-10', -821271], ['Oct-10', 693918], ['Nov-10', 416278], ['Dec-10', -974163], ['Jan-11', 860159], ['Feb-11', -1115009], ['Mar-11', 1033048], ['Apr-11', 95318], ['May-11', -308093], ['Jun-11', 99052], ['Jul-11', -521393], ['Aug-11', 605450], ['Sep-11', 231727], ['Oct-11', -65187], ['Nov-11', -702716], ['Dec-11', 177975], ['Jan-12', -1065544], ['Feb-12', 1926159], ['Mar-12', -917805], ['Apr-12', 898730], ['May-12', -334262], ['Jun-12', -246499], ['Jul-12', -64055], ['Aug-12', -1529236], ['Sep-12', 1497596], ['Oct-12', 304914], ['Nov-12', -635801], ['Dec-12', 398319], ['Jan-13', -183161]]