Python中两列之间的计算?

时间:2015-05-22 11:54:08

标签: python

当我尝试在两列之间进行某些计算(例如除法)时,出现错误: from itertools import izip_longest import csv with open(r"C:\Users\a.txt", 'rb') as csv1,\ open(r"C:\Users\b.txt", 'rb') as csv2, \ open(r"C:\Users\c.txt", 'rb') as csv3, \ open(r"C:\Users\out.txt", 'w') as out: spam1 = csv.reader(csv1, delimiter=',') spam2 = csv.reader(csv2, delimiter=',') spam3= csv.reader(csv3, delimiter=',') column1=list(izip_longest(*spam1))[-1] column2=list(izip_longest(*spam2))[-1] column3=list(izip_longest(*spam3))[-1] column_ratio=[] for x,y,z in izip_longest(column_ratio, column1, column2): column_ratio[x]=(float(column1[y]))/(float(column2[z])) for i,j,m,n,x in izip_longest(spam1,column1, column2, column3, column_ratio): out.write(','.join(i)+','+j+','+m+','+n+','+x+'\n') 。有人可以帮我解决这个问题吗?

MAX

1 个答案:

答案 0 :(得分:1)

当您使用CSV阅读器进行解析时,它无法知道数据应该是整数,浮点数,字符串等。所有以逗号分隔的数据都将被解析为字符串,并且它将被解析为由您决定将其转换为正确的类型。您需要将字符串强制转换为整数以将其用作索引。

采用以下CSV:

Index One, Index Two, Index Three
0,1,2

解析时:

x, y, z = reader.next()  # ['0', '1', '2']
print my_tuple[x]  # TypeError: tuple indices must be integers, not str
print my_tuple[int(x)]  # Expected result