【发布时间】:2021-11-12 18:24:38
【问题描述】:
执行涉及从 csv 文件读入的数据的计算时出错。我有一个包含 2 列的 csv 文件:日期和利润列。我必须在这个文件中添加两列来计算每月的净变化。由于读入数据是一个字符串,我确保将列包装在 int() 函数中并分配给一个变量。但是当我运行代码来计算值时,它仍然认为它是一个 str 类型。
我得到 TypeError: unsupported operand type(s) for -: 'str' and 'str'
with open(csv_path, 'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter =',')
header = next(csvreader)
# append 2 new columns to header row
header.append('Net Change')
header.append('Monthly Average Change')
# loop through the csvfile row-by-row and convert columns. Only the profit column is number data, I set variables equal to the row position and use numeric functions.
for row in csvreader:
month = row[0]
profit = int(row[1]) # I wrap the int() function around this row to convert to int
beginning_balance = 0
ending_balance = 0
for profit in row:
if beginning_balance == 0:
beginning_balance = profit # set the first $ value in file
ending_balance = profit
elif beginning_balance != 0:
beginning_balance = ending_balance # ending balance of prev month is new
ending_balance = profit
net_change = beginning_balance - ending_balance
percent_change = net_change / beginning_balance
# write the calculations to the added columns per row
row.append(net_change)
row.append(percent_change)
并且代码在 net_change = beginning_balance - ending_balance 部分失败。它认为我在数学计算中使用了字符串。我用 int() 函数带来了利润。这些应该是数字。我能做什么?
【问题讨论】:
-
您后来使用
for profit in row:覆盖了profit = int(row[1])。不确定你在用for循环做什么,因为它正在遍历行的每一列,包括row[0]和row[1]已经提取为month和profit并且由于覆盖profit将是一个字符串。
标签: python csv operators typeerror