-3

in this code im trying to add the sum of values and add it to an array named array_values, but it didnt, only prints []

array_values = ([])

value = 0.0
for a in range(0, 8):
    for b in range (1, 5):
        value = value + float(klines[a][b])
        #print(value)
    np.append(array_values, value)#FIX array_values.append(value)
    print("añadiendo: ",value)
    value = 0.0

print(array_values)
2

2 Answers 2

0

Does this solve your problem?

import numpy as np

array_values = ([])

value = 0.0
for a in range(0, 8):
    for b in range (1, 5):
        value = value + float(klines[a][b])
        #print(value)
    array_values = np.append(array_values, value)
    print("añadiendo: ",value)
    value = 0.0

print(array_values)

np.append returns an ndarray.

A copy of arr with values appended to axis. Note that append does not occur in-place: a new array is allocated and filled. If axis is None, out is a flattened array.

Check the return section to understand better https://numpy.org/doc/stable/reference/generated/numpy.append.html

Sign up to request clarification or add additional context in comments.

5 Comments

Sorry, my typing mistake. Can you chack the updated code, please? @ChemiJ
It didnt work too, but i fixed removing it and writing only array_values.append(value) but i cant understand why this works and the other methods didnt.
Please check the updated code. It should work now as expected @ChemiJ
Use of np.append in a loop is in-efficient compared to list append.
alist.append(value) works in place, adding a reference to value to the list. np.append is really a call to np.concatenate, and makes a new array, with copying. np.append is not a list append clone, and should not be used in the same way.
0

Assuming klines is a 2d numeric dtype array:

In [231]: klines = np.arange(1,13).reshape(4,3)
In [232]: klines
Out[232]: 
array([[ 1,  2,  3],
       [ 4,  5,  6],
       [ 7,  8,  9],
       [10, 11, 12]])

we can simple sum across rows with:

In [233]: klines.sum(axis=1)
Out[233]: array([ 6, 15, 24, 33])

the equivalent using your style of iteration:

In [234]: alist = []
     ...: value = 0
     ...: for i in range(4):
     ...:     for j in range(3):
     ...:         value += klines[i,j]
     ...:     alist.append(value)
     ...:     value = 0
     ...: 
In [235]: alist
Out[235]: [6, 15, 24, 33]

Use of np.append is slower and harder to get right.

Even if klines is a list of lists, the sums can be easily done with:

In [236]: [sum(row) for row in klines]
Out[236]: [6, 15, 24, 33]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.