【发布时间】:2018-09-21 10:08:42
【问题描述】:
我有不同大小的列表,例如
a = [1,2,3]
b = [4,5]
并且我想在短列表没有可用数据的地方创建一个包含这些值和默认值的二维数组。
c = do_something_with_a_b()
In: c
Out: array([[1,2,3],
[4,5, DEFAULT_VALUE]])
目前我使用以下内容,但我认为这过于复杂:
all_ar = []
all_ar.append(a)
all_ar.append(b)
# Get the size of all arrays for masking
len_ar = np.array([array.size for array in all_ar])
# Create a mask according to the length of the arrays
mask = np.arange(len_ar.max()) < len_ar[:,None]
# Create an array filled with the default value, here -1
c = np.full(mask.shape, -1, dtype='int')
# Use the mask to overwrite the the default values with the
# data from the arrays
c[mask] = np.concatenate(all_ar)
In: c
Out: array([[1,2,3],
[4,5,-1]])
有没有更简单的方法可以将不规则大小的列表转换为具有规则形状和缺失数据点处的默认值的 numpy 数组?
【问题讨论】:
标签: python numpy multidimensional-array