Tom Lowbridge Tom Lowbridge - 1 year ago 55
Python Question

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.

with open('CLASSES.csv', 'rt')as f:
for column in reader:

difference = [x[3] for x in people] - [x[4] for x in people]

I get the error TypeError: unsupported operand type(s) for -: 'list' and 'list' when this. I know why I get the error but I can't think of a way around it.

Any help would be great!

Answer Source

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. 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.

Using numpy and it's genfromtxt function:

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.

The dtype=None option lets genfromtxt automatically decide the type for each column, default is float.