【发布时间】:2021-04-12 23:37:02
【问题描述】:
我有 N 个形状为 data[n,m,3] 的 NumPy 数组。我想将它们拟合/挤压/拆分/切片/重塑成 N' 个形状为 new_data_#[1000,m,3] 的数组,其中 # 是新数组的索引。问题是 n 可以小于或大于 1000。当它以某种方式较小时,我应该用下一个数组填充 new_array 的其余 1000 个容量,当它大于 1000 时,我应该创建一个 new_data_# 并添加休息到那个。我不知道如何管理这个。这是一个伪代码,但不能以这种方式完成,例如,while 可能不是必需的。输出可以写入磁盘或以新的数据格式返回。
def array2blocks(array_files)
for each N in array_files:
N = data = np.random.rand(n, m, 3)
new_data = np.zeros((1000, m, 3), dtype=np.float32)
j=0
index = 0
while j <= new_data.shape[0]:
for i in range(data.shape[0]):
print("--->", data[i,:,:])
print (i)
if i <= new_data.shape[0]:
# here first we should check the left capacity of new_data and then insert data into it
# new_data[i, :, :] = data[i, :, :] #this overrides previous items so not correct
print(new_data)
else:
print('n>1000')
new_data_name = 'new_data' + '_' + str(index)
# here fill rest of the data in the new_data
...
index += 1
#when capacity is full write it to the disk
print(new_data)
UPDATE 与 Aaron 的旧答案:
我将 1000 替换为 batch_size = 5 以使其变得简单。
def numpyarrays2blocks(array_files):
N1 = np.random.rand(7, 4, 3)
N2 = np.random.rand(7, 4, 3)
N3 = np.random.rand(4, 4, 3)
# array_files = []
array_files.append(N1)
array_files.append(N2)
array_files.append(N3)
for N in array_files:
n = N.shape[0]
m = N.shape[1]
batch_size = 5
# N = data = np.random.rand(n, m, 3)
data = N
# print(data)
new_arrays = []
i = 0 # the current row index to insert
while i < n:
new_data = np.zeros((batch_size, m, 3), dtype=np.float32)
j = min(i + batch_size, n) # the last row (exclusive) to copy to new_data
# j - i is the number of rows to copy
new_data[:j - i, :, :] = data[i:j, :, :]
print('NEW DATA: ', new_data)
i = j # update the index
new_arrays.append(new_data)
print(new_arrays)
【问题讨论】: