How to sum the frist index in numpy array

Question:

How to sum the first index of array with the number of iterations the max number iteration is 2.

I’ve tried use below code, but I still get wrong result for index number 2.

a = np.array([[858,833,123],
[323,542,927],
[938,361,271],
[679,272,451]])

max_iter = 2
for i in range(max_iter):
    for j in range(len(a)):
        a[j][0] += i

the results from the code above :

[[859 833 123]
 [324 542 927]
 [939 361 271]
 [680 272 451]]

my expected results is:

[859,833,123],
[325,542,927],
[939,361,271],
[681,272,451]
Asked By: stack offer

||

Answers:

You’re almost there! You’re just adding the wrong value.

The key problem is that you are continuously increasing i.
In reality (I think) you want to add 1 on the first row, 2 on the second, 1 on the third and 2 on the fourth.

Remember the row numbers are index from 1. Therefore you can do % 2 so that the first row, #0, gives 0. You can add 1 to that, to give the increment you want, which is 1.

The second row, #1, gives 1; when you add 1, you get 2, which is the correct increment for that row.

The third row, #2, gives 0; when you add 1, you get 1, which is the correct increment for that row, and so on.

a = np.array([[858,833,123],
[323,542,927],
[938,361,271],
[679,272,451]])

max_iter = 2
for row in range(len(a)):
        increment = (row % max_iter) +1 
        a[row][0] += increment
Answered By: Eureka

The question is not clear about requirements, i just take a guess that you want to add a number in range (1, max_iterator) to rows in order, for example:

  • add 1 to row 1st
  • add 2 to row 2nd
  • add 1 to row 3rd
  • add 2 to row 4th
  • and 1 to row 5th
  • and so on

If so, you can do it by following:

a = np.array([[858,833,123],
             [323,542,927],
             [938,361,271],
             [679,272,451]])
max_iter = 2
iter = 0
for i in range(len(a)):
    a[i][0] = a[i][0] + (iter % max_iter) + 1
    iter += 1
print(a)

Output will be as expected:

[859,833,123],
[325,542,927],
[939,361,271],
[681,272,451]
Answered By: TaQuangTu

You can repeat 1 and 2 to len(a) size then add them to the first column of arr

max_iter = 2
arr = [(i % max_iter)+1 for i in range(len(a))]
a[:, 0] += arr
$ print(arr)

[1, 2, 1, 2]

$ print(a)

[[859 833 123]
 [325 542 927]
 [939 361 271]
 [681 272 451]]
Answered By: Ynjxsjmh
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.