[英]Transform numpy array to incorporate inside arrays
I have a multidimensional numpy array of dtype object, which was filled with other arrays.我有一个 dtype object 的多维 numpy 数组,其中填充了其他 arrays。 As an example, here is a code reproducing that behavior:
例如,下面是重现该行为的代码:
arr = np.empty((3,4,2,1), dtype=object)
for i in range(arr.shape[0]):
for j in range(arr.shape[1]):
for k in range(arr.shape[2]):
for l in range(arr.shape[3]):
arr[i, j, k, l] = np.random.random(10)
Since all the inside arrays have the same size, I would like in this example to "incorporate" the last level into the array and make it an array of size (3,4,2,1,10).由于 arrays 内部的所有大小都相同,因此我想在此示例中将最后一级“合并”到数组中,并使其成为大小为 (3,4,2,1,10) 的数组。 I cannot really change the above code, so what I am looking for is a clean way (few lines, possibly without for loops) to generate this new array once created.
我无法真正更改上面的代码,所以我正在寻找一种干净的方式(几行,可能没有 for 循环)来生成这个新数组一旦创建。
Thank you.谢谢你。
If I understood well your problem you could use random.random_sample()
which should give the same result:如果我很好地理解了您的问题,您可以使用
random.random_sample()
应该给出相同的结果:
arr = np.random.random_sample((3, 4, 2, 1, 10))
After edit the solution is arr = np.array(arr.tolist())
编辑后的解决方案是
arr = np.array(arr.tolist())
Just by adding a new for
loop:只需添加一个新
for
循环:
arr = np.empty((3,4,2,1,10), dtype=object)
for i in range(arr.shape[0]):
for j in range(arr.shape[1]):
for k in range(arr.shape[2]):
for l in range(arr.shape[3]):
for m in range(arr.shape[4]):
arr[i, j, k, l, m] = np.random.randint(10)
However, you can one line this code with an optimized numpy function, every random function from numpy has a size
parameter to build a array
with random number with a particular shape: However, you can one line this code with an optimized numpy function, every random function from numpy has a
size
parameter to build a array
with random number with a particular shape:
arr = np.random.random((3,4,2,1,10))
EDIT:编辑:
You can flatten the array, replace every single number by a 1D array of length 10 and then reshape it to your desired shape:您可以展平数组,用长度为 10 的一维数组替换每个数字,然后将其重塑为所需的形状:
import numpy as np
arr = np.empty((3,4,2,1), dtype=object)
for i in range(arr.shape[0]):
for j in range(arr.shape[1]):
for k in range(arr.shape[2]):
for l in range(arr.shape[3]):
arr[i, j, k, l] = np.random.randint(10)
flat_arr = arr.flatten()
for i in range(len(flat_arr)):
flat_arr[i] = np.random.randint(0, high=10, size=(10))
res_arr = flat_arr.reshape((3,4,2,1))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.