将多个元素追加到numpy数组

时间:2018-08-15 21:36:01

标签: python arrays numpy

我有8个元素,我想将它们添加到numpy数组中。我使用了np.append(),但似乎一次只能添加两个元素。我想一次添加所有8元素。 first_1 =35.72438966508524first_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

3 个答案:

答案 0 :(得分:1)

np.array([first_1,first_2,first_3,first_4,first_5,first_6,first_7,first_8])

答案 1 :(得分:1)

正确的语法是(如果我想您要将8个值附加到名为ar的numpy数组中:

np.append(ar, (first_1, first_2, first_3, first_4, first_5, first_6, first_7, first_8))
  • first 参数是您原始的numpy数组
  • 第二个 是您的值的 tuple (或 list ,或其他类似数组的对象),因此这些值< em>必须在括号中。

答案 2 :(得分:0)

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