Tom Lowbridge - 10 months ago 36

Python Question

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:`

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

Any help would be great!

Answer

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`

.