batuman
batuman

Reputation: 7304

Get column from 2D list in Python

I have a 2D list and like to get individual column from the list.

          X=[]
          for line in lines:
             c,xmin,ymin,xmax,ymax = line.split(' ')
             xmin_ = float(xmin)
             ymin_ = float(ymin)
             xmax_ = float(xmax)
             ymax_ = float(ymax)
             area_ = (xmax_ - xmin_)*(ymax_ - ymin_)
             X.append(xmax_-xmin_, ymax_-ymin_, area_)

If I print column values, I have error as

>>>X[:,1]

*** TypeError: list indices must be integers, not tuple

But why the following example works

>>> a = arange(20).reshape(4,5)

>>> a
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

>>> a[:, 1]
array([ 1,  6, 11, 16])

What is the difference?

Upvotes: 0

Views: 4452

Answers (1)

Junhee Shin
Junhee Shin

Reputation: 758

you can change the list to numpy array.

import numpy as np
x=[[1,2,3],[4,5,6]]
x[:,1]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: list indices must be integers, not tuple
xa = np.array(x)
xa
array([[1, 2, 3],
       [4, 5, 6]])
xa[:,1]
array([2, 5])

Upvotes: 3

Related Questions