简体   繁体   中英

Appending multiple elements to numpy array

I have 8 elements and I want to add them into a array in numpy. I used np.append() but it seems that I can only add two elements at one time. I want to add all 8 elements at once. first_1 =35.72438966508524 , first_2 = 35.73839550991734 , etc.

35.72438966508524 35.73839550991734 35.81944190992304 
35.80549149559467 35.78399019604507 36.03781192909738 
35.9957696566448 35.94692998938782

np.append(first_1,first_2,first_3,first_4,first_5,first_6,first_7,first_8)

The error is

TypeError: append() takes from 2 to 3 positional arguments but 8 were given
np.array([first_1,first_2,first_3,first_4,first_5,first_6,first_7,first_8])

Correct syntax is (if I suppose that you wanted to append your 8 values to an numpy array named as ar :

np.append(ar, (first_1, first_2, first_3, first_4, first_5, first_6, first_7, first_8))
  • The first argument is your original numpy array,
  • The second one is the tuple (or the list , or other array-like object) of your values, so those values have to be in the parentheses .
first = 35.72438966508524 
second = 35.73839550991734 
third = 35.81944190992304
forth = 35.80549149559467 
fifth = 35.78399019604507 
sixth = 36.03781192909738 
seventh = 35.9957696566448 
eighth = 35.94692998938782

now to make a new numpy array:

a = np.array([first, second, third, forth, fifth, sixth, seventh, eighth])

output:

a
Out[89]: 
array([35.72438967, 35.73839551, 35.81944191, 35.8054915 , 35.7839902 ,
       36.03781193, 35.99576966, 35.94692999])

to append to existing array (using previously created 'a'):

a = np.append(a, [first, second, third, forth, fifth, sixth, seventh, eight], axis=0)

which gives:

a
Out[93]: 
array([35.72438967, 35.73839551, 35.81944191, 35.8054915 , 35.7839902 ,
       36.03781193, 35.99576966, 35.94692999, 35.72438967, 35.73839551,
       35.81944191, 35.8054915 , 35.7839902 , 36.03781193, 35.99576966,
       35.94692999])

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