CSV中的行和

  • 本文关键字:CSV python csv
  • 更新时间 :
  • 英文 :


我有以下代码:

with open("expenses.csv") as read_exp:
reader = csv.reader(read_exp, delimiter=',')
header = next(reader)
if header != None:
for row in reader:
month_str = row[0]
month_dt= datetime.strptime(month_str, '%d/%m/%Y').month       
if month_dt == month1:
sum1 = sum((map(int,row[2:7])))
print(sum1)

这给了我从我正在寻找的月份开始的每一行的总和。

输出:

Enter selected month number: 7
Selected Month is: July
15
26
7
23
21
19
30

是否有办法将单个的总和合并为一个总和?

我的csv如下:

Date,Budget,Groceries,Transport,Food,Bills,Others
12/7/2021,30,1,0,4,2,8
13/7/2021,30,9,3,5,7,2
14/7/2021,30,3,3,0,0,1
15/7/2021,30,1,0,10,7,5
16/7/2021,30,9,9,0,2,1
17/7/2021,30,0,6,4,1,8
18/7/2021,30,0,9,9,8,4
16/8/2021,30,7,10,7,10,1
17/8/2021,30,5,6,10,9,1
18/8/2021,30,6,1,9,10,5
19/8/2021,30,0,8,8,3,5
20/8/2021,30,4,0,6,9,4
21/8/2021,30,6,2,1,1,5
22/8/2021,30,3,3,1,1,10
13/9/2021,30,8,2,9,4,6
14/9/2021,30,10,7,10,5,7
15/9/2021,30,5,5,6,9,6
16/9/2021,30,5,7,4,6,2
17/9/2021,30,3,7,10,5,7
18/9/2021,30,8,9,6,8,1
19/9/2021,30,5,3,1,9,5

我假设您想在示例中打印当月的完整值,对吗?

如果是这种情况,您可以使用一个变量total_sum,例如,您可以将sum1的内容(假设sum1是一个值)添加到其中,如下所示:

reader = csv.reader(read_exp, delimiter=',')
header = next(reader)
if header != None:
for row in reader:
month_str = row[0]
month_dt= datetime.strptime(month_str, '%d/%m/%Y').month       
if month_dt == month1:
sum1 = sum((map(int,row[2:7])))
print(sum1)
total_sum += sum1
print(total_sum)

相关内容

  • 没有找到相关文章

最新更新