我已经从CSV文件中导入了值,该文件在第1列中有日期,在第2列中有美元值。我打开它,计算了每行每月的变化。这些更改mthchangeprofit
已附加到列表monthlychange
中
我想用monthlychange
的和除以count
(6)来计算平均月变化。我已将monthlychange
转换为名为sum_mthly
的float
。平均变化应计算为-450美元/6=-75美元。数据文件中不存在C列和D列。为了便于比较,我将它们添加到图像中
两个问题:
sum_mthly
正在获取上一个月的变化,而不是将整个列表相加
尽管是integer
,但如果没有“浮点零除错误”,我不能用countofchanges
替换数字6。它打印出“6”
# Open the CSV.
with open(file, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
csvheader = next(csvreader)
# Initialize variables as zero.
count = 0
beginprofit = 0
# Conducting the ask
for row in csvreader:
#Count the number months.
count = count + 1
# Create data lists to append data rows to.
monthlychange = []
#Calculate the monthly change in profits.
endprofit = int(row[1])
mthchangeprofit = endprofit - beginprofit
#Store these monthly changes in a list
monthlychange.append(mthchangeprofit)
beginprofit = endprofit
#Calculate the avg change in profits
countofchanges = count - 1 #denominator
sum_mthly = sum(float(mthchangeprofit) for mthchangeprofit in monthlychange) #numerator
avgchange_profits = sum_mthly/6 #only using last mthly change
print(type(mthchangeprofit)) #integer
print(type(monthlychange)) #list
print(type(sum_mthly)) #float
print(type(countofchanges)) #integer
print("----------------------------------------------------------")
print("Count of Changes: " + str(countofchanges)) #prints "6"
print("Average Change: " + "$" + str(int(avgchange_profits))) #prints "$16"
目前没有回答
相关问题 更多 >
编程相关推荐