[英]csv - take away data of one column from another
I want to take the value of column 4 from column 3 (their both integers), this is what I have. 我想从第3列中获取第4列的值(它们都是整数),这就是我所拥有的。
with open('CLASSES.csv', 'rt')as f:
reader=csv.reader(f)
people=[]
for column in reader:
people.append(column[0:8])
difference = [x[3] for x in people] - [x[4] for x in people]
print(difference)
I get the error TypeError: unsupported operand type(s) for -: 'list' and 'list' when this. 我收到错误TypeError:-的不支持的操作数类型-:“列表”和“列表” 。 I know why I get the error but I can't think of a way around it. 我知道为什么会收到错误,但我想不出办法解决。
Any help would be great! 任何帮助将是巨大的!
Like @Peter Wood said in the comment, you need to subtract inside of one list comprehension, not doing two list comprehension as this results in list - list
. 就像@Peter Wood在评论中说的那样,您需要在一个列表理解中减去,而不是在两个列表理解中进行减法,因为这会导致list - list
。 Also you need to convert to numbers. 另外,您需要转换为数字。
difference = [int(x[3]) - int(x[4]) for x in people]
If you want to do stuff like this, you are probably better off using numpy
or even pandas
. 如果您想做这样的事情,最好使用numpy
甚至pandas
。
Using numpy and it's genfromtxt
function: 使用numpy及其genfromtxt
函数:
import numpy as np
people = np.genfromtxt('CLASSES.txt', delimiter=',', dtype=None)
difference = people[:, 3] - people[:, 4]
Here people
will be a two dimensional numpy array, this first index going over the rows, second over the columns [:, 3]
takes every row of the thirds column. 这里的people
将是一个二维的numpy数组,第一个索引遍历行,第二个索引遍历列[:, 3]
占据三分之一列的每一行。
The dtype=None
option lets genfromtxt
automatically decide the type for each column, default is float
. genfromtxt
dtype=None
选项使genfromtxt
自动确定每一列的类型,默认值为float
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.