【问题标题】:Python array with fixed length but with sequential filling of new values具有固定长度但顺序填充新值的 Python 数组
【发布时间】:2019-07-18 05:52:51
【问题描述】:

假设我们有一个变量(形状(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】:

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

    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)
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-14
    相关资源
    最近更新 更多