假设我有一个大小为20x10的二维numpy阵列。
我还有一个长度为20的数组,del_ind。
我想根据del_ind从A的每一行中删除一个元素,以得到一个大小为20x9的结果数组。
我该怎么做?
我使用指定的axis = 1查看了np.delete,但这只删除了每一行相同位置的元素。
谢谢你的帮助
发布于 2015-11-23 15:08:39
您可能需要构建一个新的数组。
幸运的是,您可以避免对此任务使用python循环,使用奇特的索引:
h, w = 20, 10
A = np.arange(h*w).reshape(h, w)
del_ind = np.random.randint(0, w, size=h)
mask = np.ones((h,w), dtype=bool)
mask[range(h), del_ind] = False
A_ = A[mask].reshape(h, w-1)
使用较小的数据集进行演示:
>>> h, w = 5, 4
>>> %paste
A = np.arange(h*w).reshape(h, w)
del_ind = np.random.randint(0, w, size=h)
mask = np.ones((h,w), dtype=bool)
mask[range(h), del_ind] = False
A_ = A[mask].reshape(h, w-1)
## -- End pasted text --
>>> A
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15],
[16, 17, 18, 19]])
>>> del_ind
array([2, 2, 1, 1, 0])
>>> A_
array([[ 0, 1, 3],
[ 4, 5, 7],
[ 8, 10, 11],
[12, 14, 15],
[17, 18, 19]])
发布于 2015-11-23 15:05:05
Numpy并不以内部编辑而闻名;它主要用于静态大小的矩阵。因此,我建议将预期的元素复制到一个新的数组中。
假设从每一行中删除一列就足够了:
def remove_indices(arr, indices):
result = np.empty((arr.shape[0], arr.shape[1] - 1))
for i, (delete_index, row) in enumerate(zip(indices, arr)):
result[i] = np.delete(row, delete_index)
return result
https://stackoverflow.com/questions/33882265
复制