簡體   English   中英

將多個元素附加到numpy數組

[英]Appending multiple elements to numpy array

我有8元素,我想將它們添加到 numpy 中的數組中。 我使用了np.append()但似乎一次只能添加兩個元素。 我想一次添加所有8元素。 first_1 =35.72438966508524 , first_2 = 35.73839550991734

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)

錯誤是

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])

正確的語法是(如果我假設您想將 8 個值附加到名為ar的 numpy 數組:

np.append(ar, (first_1, first_2, first_3, first_4, first_5, first_6, first_7, first_8))
  • 一個參數是你原來的 numpy 數組,
  • 第二個是值的元組(或列表或其他類似數組的對象),因此這些值必須在括號中
first = 35.72438966508524 
second = 35.73839550991734 
third = 35.81944190992304
forth = 35.80549149559467 
fifth = 35.78399019604507 
sixth = 36.03781192909738 
seventh = 35.9957696566448 
eighth = 35.94692998938782

現在創建一個新的 numpy 數組:

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

輸出:

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

附加到現有數組(使用先前創建的“a”):

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

這使:

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])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM