我在 python 中有一个名为 my_values
的 numpy
数组,大小为 5x5,还有一个 numpy
向量,其中包含大小为 1x90 的 bool 值(5 False , 85 True) naned cols_indexes。我想用等于 False
的 cols_indexes 位置索引中的零来扩展我的初始数组 my_values
。因此,最终我的转换矩阵 my_values
的大小应为 5x90(其中 85 个新列填充为零)。使用数组而不是 bool 向量的简单示例是:
def insert_one_per_row(arr, mask, putval):
mask_ext = np.column_stack((mask, np.zeros((len(mask), 1), dtype=bool)))
out = np.empty(mask_ext.shape, dtype=arr.dtype)
out[~mask_ext] = arr.ravel()
out[mask_ext] = putval
return out
y = np.arange(25).reshape(5, 5)
x = np.array([[False, True, False, False, False],
[False, True, False, False, False],
[False, True, False, False, False],
[False, True, False, False, False],
[False, True, False, False, False]], dtype=bool)
arr = insert_one_per_row(y, x, putval=0)
此示例适用于 bool 数组。然而在我的例子中,x 是一个向量而不是一个数组。 x
对于我需要添加的位置中的新列包含 True
,对于最终数组位置中的现有列包含 False
。如何使用向量 x
而不是矩阵 x
插入新列?
最佳答案
您的输入 - 调整以适应工作:
In [73]: y = np.arange(1,21).reshape(5, 4)
...: x = np.array([[False, True, False, False, False],
...: [False, True, False, False, False],
...: [False, True, False, False, False],
...: [False, True, False, False, False],
...: [False, True, False, False, False]], dtype=bool)
...:
整个数组屏蔽,大致是你的函数的作用
In [74]: res = np.full(x.shape, 0) # assign the putval on creation
In [75]: res[~x] = y.ravel()
In [76]: res
Out[76]:
array([[ 1, 0, 2, 3, 4],
[ 5, 0, 6, 7, 8],
[ 9, 0, 10, 11, 12],
[13, 0, 14, 15, 16],
[17, 0, 18, 19, 20]])
我们可以使用 where
从 1d 掩码中获取列索引,这里是一行 x
:
In [77]: res[:, np.where(~x[0,:])[0]]
Out[77]:
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15, 16],
[17, 18, 19, 20]])
赋值 - 但不要使用 ravel,因为 RHS 是 (4,5)。此索引不会像完整 bool 掩码那样展平数组:
In [80]: res[:, np.where(~x[0,:])[0]] = 2*y
In [81]: res
Out[81]:
array([[ 2, 0, 4, 6, 8],
[10, 0, 12, 14, 16],
[18, 0, 20, 22, 24],
[26, 0, 28, 30, 32],
[34, 0, 36, 38, 40]])
关于python - 将新列插入 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49755715/