删除一些元素并在 Python 中展平数组

Deleting some elements and flattening the array in Python

我有一个数组,R。我想删除与 Remove 中的索引对应的元素,然后用剩余的元素展平。附上所需的输出。

R=np.array([[1.05567452e+11, 1.51583103e+11, 5.66466172e+08],
       [6.94076420e+09, 1.96129124e+10, 1.11642674e+09],
       [1.88618492e+10, 1.73640817e+10, 4.84980874e+09]])

Remove = [(0, 1),(0,2)] 

R1 = R.flatten()
print([R1])

期望的输出是

array([1.05567452e+11, 6.94076420e+09, 1.96129124e+10, 1.11642674e+09,
       1.88618492e+10, 1.73640817e+10, 4.84980874e+09])
R = np.array([[1.05567452e+11, 1.51583103e+11, 5.66466172e+08],
              [6.94076420e+09, 1.96129124e+10, 1.11642674e+09],
              [1.88618492e+10, 1.73640817e+10, 4.84980874e+09]])

R1 = np.delete(R, (1, 2))

print([R1])

你可以用列表理解来做到这一点:

import numpy as np
R=np.array([[1.05567452e+11, 1.51583103e+11, 5.66466172e+08],
       [6.94076420e+09, 1.96129124e+10, 1.11642674e+09],
       [1.88618492e+10, 1.73640817e+10, 4.84980874e+09]])

Remove = [(0, 1),(0,2)] 
b = [[j for i, j in enumerate(m) if (k, i) not in Remove] for k, m in enumerate(R)]
R1 = np.array([i for j in b for i in j]) #Flatten the resulting list

print(R1)

输出

array([1.05567452e+11, 6.94076420e+09, 1.96129124e+10, 1.11642674e+09,
       1.88618492e+10, 1.73640817e+10, 4.84980874e+09])

一种选择是使用 numpy.ravel_multi_index 获取扁平数组中 Remove 的索引,然后使用 numpy.delete:

删除它们
out = np.delete(R, np.ravel_multi_index(tuple(zip(*Remove)), R.shape))

另一个可能是替换 Remove 中的值,然后展平 R 并过滤掉这些元素:

R[tuple(zip(*Remove))] = R.max() + 1
arr = R.ravel()
out = arr[arr<R.max()]

输出:

array([1.05567452e+11, 6.94076420e+09, 1.96129124e+10, 1.11642674e+09,
       1.88618492e+10, 1.73640817e+10, 4.84980874e+09])
import numpy as np

R = np.array([[1.05567452e+11, 1.51583103e+11, 5.66466172e+08],
              [6.94076420e+09, 1.96129124e+10, 1.11642674e+09],
              [1.88618492e+10, 1.73640817e+10, 4.84980874e+09]])

Remove = [(0, 1), (0, 2)]
Remove = [R.shape[1]*i+j for (i, j) in Remove]
print(np.delete(R, Remove))