具有固定长度但顺序填充新值的Python数组

问题描述 投票:1回答:1

让我们假设我们有一个变量(形状(1,N,a,b,c)),它存储具有形状(a,b,c)的numpy数组。我首先要用零初始化这个变量

import numpy as np
N = 5
a = 20
b = 40
c = 4
storage = np.zeros(1, N, a, b, c)
# collect new arrays
while True:
    values = np.random.random((a, b, c))  # np.array with shape (a, b, c)
    save_values_to_storage(values)

函数save_values_to_storage(values)的目标是填充存储中的值。在第一个循环中,存储的(1,N,...)值将用values填充。在下一个循环(1,N,...)中,存储的值将用values填充,之前的值将移动到(1,N-1,...)。等等。如果第一次存储values到达第一个位置(1,1,...)并且检索并存储新的values,则第一个values将被抛弃,使得新的values被存储在位置(1,N,...)并且所有其他价值因其位置而减少。

我不知道如何才能实现这样的行为。它类似于numpy数组的队列。所以我的问题是如何实现save_values_to_storage(values)功能?

编辑:似乎deque是相似的。但我不知道如何将它们用于numpy数组

python numpy queue deque
1个回答
0
投票

我想我解决了这个问题。我不确定这是否是最好的方法。我感谢任何改进。

import numpy as np
import random

N = 5
a = 20
b = 40
c = 4
inputs = np.zeros((N, a, b, c))
for i in range(0, 10):
    # replace right hand side with method that gets values
    values = np.random.random((a, b, c))
    # expand the dimension to fit to inputs
    values = np.expand_dims(values, axis=0)
    # delete values in first entry of inputs
    inputs = np.delete(inputs, obj=0, axis=0)
    # concatenate inputs and values to a new array
    inputs = np.concatenate([inputs, values], axis=0)
    # for debugging
    # print('shape: {}'.format(inputs.shape))

# expand the dimension with an additional first dimension to achieve (1, N, a, b, c)  # shape.
inputs = np.expand_dims(inputs, axis = 0)
© www.soinside.com 2019 - 2024. All rights reserved.