简体   繁体   中英

Numpy arrays (append, concatenate)

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?

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM