2

I want to set value of numpy array as following. But I don't want to use for-loop. Is there any good way?

a = range(4)
a[0] = [11,12,13,14,15,16]
a[1] = [21,22,23,24,25,26]
a[2] = [31,32,33,34,35,36]
a[3] = [41,42,43,44,45,46]

a = np.array(a)

changeIndex = [0,2,4]
for i in range(4):
    a[i][changeIndex] = 0

print a
#array([[ 0, 12,  0, 14,  0, 16],
#       [ 0, 22,  0, 24,  0, 26],
#       [ 0, 32,  0, 34,  0, 36],
#       [ 0, 42,  0, 44,  0, 46]])
Pacific Stickler
  • 1,078
  • 8
  • 20
Kei Minagawa
  • 4,395
  • 3
  • 25
  • 43

2 Answers2

9

you essentially want to access multiple columns, which you can do by:

a[:, changeIndex] = 0

Remember:

  1. First index selects the rows, while the second index select the columns.
  2. You can select multiple indices using a list or a tuple.

Better Style:

Also a better way for you to define your multi-dimensional numpy array or matrix would be:

a = np.array([range(11,17), range(21,27), range(31, 37), range(41,47)])

And thanks to one of the comments, you can actually use np.arange() in place of range() for faster computation

Matrices:

When working on 2D arrays consider using a Matrix instead. Matrices retain their multi-dimensional nature as you perform operations on them, and you can also use special matrix operations on them. Read here. They work similar to arrays as well:

a = np.matrix([range(11,17), range(21,27), range(31, 37), range(41,47)])

A somewhat related thread for your reference is here.

Community
  • 1
  • 1
Pacific Stickler
  • 1,078
  • 8
  • 20
  • Using `np.arange` is even in this case with small intervals 2x faster than `range`. – sebix Sep 06 '14 at 08:24
  • 1
    And using `np.vstack((...))` or similar methods are always faster than `np.array([...])` (9x in my test now) – sebix Sep 06 '14 at 08:43
2

I am assuming you do not want to use 'for' loop to iterate over all the rows. With numpy, you do not have to go that way.

You can just use

a[:, changeIndex] = 0

With numpy, changeIndex can be a integer(Changing only one column) or changeIndex can be a list(Enabling you to change multiple columns).

doubleo
  • 4,389
  • 4
  • 16
  • 19