np.append 只给出附加的最后一个值? [英] np.append only giving last value appended?
问题描述
在下面的代码中,我尝试使用 np.append
但它只给了我附加在循环中的最后一个值.
In the code below I tried to use np.append
but it only gives me the last value appended in the loop.
我有两个嵌套的 for 循环(一个使用索引 i
运行,另一个使用 k
运行).现在我想为不同的索引执行某个函数,并且我希望将结果汇总在一个数组中.这样数组中的每一行都包含一个索引的结果.
I have two nested for loops (one runs with index i
, the other one with k
). Now I want to exercise a certain function for different indices and I want the outcomes to be summarized in one array. So that each line in the array contains the outcome for one index.
这是一个最小的可重现示例:
Here a minimal reproducible example:
import numpy as np
a = np.arange(0,2,1)
b = np.arange(3,5,1)
c = np.array([])
for i in range(0,2,1):
for k in range(0,2,1):
c = np.append(a[i],b[k])
print(c)
结果是[1 4]
.但我想要一个包含 ([0 3][0 4][1 3][1 4])
The outcome is [1 4]
. But I want one single vector c
containing ([0 3][0 4][1 3][1 4])
推荐答案
您正在创建一维数组而不是二维数组.并在 np.append
您必须传递当前数组和附加元素,它将返回一个新数组.
You are creating 1d array instead of 2d. and in np.append
you have to pass current array and appending elements and it will return a new array.
a = np.arange(0,2,1)
b = np.arange(3,5,1)
c = np.empty(shape=[0, 2])
for i in range(0,2,1):
for k in range(0,2,1):
c = np.append(c,[[a[i],b[k]]],axis=0)
print(c)
输出:
[[0. 3.]
[0. 4.]
[1. 3.]
[1. 4.]]
这篇关于np.append 只给出附加的最后一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!