0

I'm trying to add "average" to other numpy array "all averages", but append, concatenate returns with errors:

n1, n2, n3  = 5 , 16, 27
all_averages = np.array ([], dtype = float)
for i in range(1000):
    sample_2 = pareto.rvs (7, size = n1)
    average = np.array([np.average(sample_2)])
    all_averages.append(average)

'numpy.ndarray' object has no attribute 'append'

n1, n2, n3  = 5 , 16, 27
all_averages = np.array ([], dtype = float)
for i in range(1000):
    sample_2 = pareto.rvs (7, size = n1)
    average = np.array([np.average(sample_2)])
    np.concatenate((all_averages, average))
print(all_averages)

[]

What am I missing?

2 Answers 2

1

Numpy arrays are not like python lists, they have a fixed size. That's why you won't find an append method.

However, you're really close to the solution: np.concatenate does not work in-place, but returns the concatenate array. You should look around

all_averages = np.concatenate((all_averages, average))

To be even more efficient, try to do only one concatenate operation. Store all averages in a list, and concatenate them all together afterwards. That way, you'll avoid unnecessary copies between arrays

n1, n2, n3  = 5 , 16, 27
all_averages_list = []
for i in range(1000):
    sample_2 = pareto.rvs (7, size = n1)
    average = np.array([np.average(sample_2)])
    all_averages_list.append(average)
all_averages = np.concatenate(all_averages_list, axis=0) # check axis param, I'm not sure here
print(all_averages)
Sign up to request clarification or add additional context in comments.

Comments

1

Also, in addition to @Grégoire Roussel you can do the same with append() which has the following signature: numpy.append(arr, values, axis=None)

Therefore, you'd have to do the following (last line changed):

n1, n2, n3  = 5 , 16, 27
all_averages = np.array ([], dtype = float)
for i in range(1000):
    sample_2 = pareto.rvs (7, size = n1)
    average = np.array([np.average(sample_2)])
    all_averages = np.append(all_averages, average)

1 Comment

still, appending to a list is computationally expensive. I'd suggest to define the array with a needed size a priori and then fill the array.

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.