我正在尝试填充 NumPy 数组的 NumPy 数组。每次我完成循环的迭代时,我都会创建要添加的数组。然后我想将该数组附加到另一个数组的末尾。例如:
first iteration
np.append([], [1, 2]) => [[1, 2]]
next iteration
np.append([[1, 2]], [3, 4]) => [[1, 2], [3, 4]]
next iteration
np.append([[1, 2], [3, 4]], [5, 6]) => [[1, 2], [3, 4], [5, 6]]
etc.
Run Code Online (Sandbox Code Playgroud)
我试过使用 np.append 但这返回一个一维数组,即
[1, 2, 3, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)
我发现将此代码与 numpy 一起使用很方便。例如:
loss = None
new_coming_loss = [0, 1, 0, 0, 1]
loss = np.concatenate((loss, [new_coming_loss]), axis=0) if loss is not None else [new_coming_loss]
Run Code Online (Sandbox Code Playgroud)
实际使用:
self.epoch_losses = None
self.epoch_losses = np.concatenate((self.epoch_losses, [loss.flatten()]), axis=0) if self.epoch_losses is not None else [loss.flatten()]
Run Code Online (Sandbox Code Playgroud)
复制粘贴解决方案:
def append(list, element):
return np.concatenate((list, [element]), axis=0) if list is not None else [element]
Run Code Online (Sandbox Code Playgroud)
警告:除了第一个维度之外,列表和元素的维度应该相同,否则您将得到:
ValueError: all the input array dimensions except for the concatenation axis must match exactly
Run Code Online (Sandbox Code Playgroud)
小智 5
嵌套数组,使它们具有多个轴,然后在使用append
.
import numpy as np
a = np.array([[1, 2]]) # note the braces
b = np.array([[3, 4]])
c = np.array([[5, 6]])
d = np.append(a, b, axis=0)
print(d)
# [[1 2]
# [3 4]]
e = np.append(d, c, axis=0)
print(e)
# [[1 2]
# [3 4]
# [5 6]]
Run Code Online (Sandbox Code Playgroud)
或者,如果您坚持使用列表,请使用numpy.vstack:
import numpy as np
a = [1, 2]
b = [3, 4]
c = [5, 6]
d = np.vstack([a, b])
print(d)
# [[1 2]
# [3 4]]
e = np.vstack([d, c])
print(e)
# [[1 2]
# [3 4]
# [5 6]]
Run Code Online (Sandbox Code Playgroud)
免责声明:附加数组应该是例外,因为它效率低下。
也就是说,您可以通过指定一个轴来实现您的目标
a = np.empty((0, 2))
a = np.append(a, [[3,6]], axis=0)
a = np.append(a, [[1,4]], axis=0)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
19168 次 |
最近记录: |