删除具有相同元素的列

问题描述 投票:0回答:1
arr_2d = np.array([[ 1,  2,  4,  9, 3, 10],
                   [ 1,  3,  4, 12, 3, 15],
                   [ 1,  6,  4, 16, 3, 22],
                   [ 1, 10,  4, 21, 3, 30]])
arr_2d_copy = arr_2d.copy()
for col_idx in range(arr_2d.shape[1]):
    are_all_same = np.all(arr_2d[:,col_idx] == arr_2d[:,col_idx][0])
    print('Same? ', are_all_same)
    if are_all_same:
        arr_2d_copy = np.delete(arr_2d_copy, col_idx, axis=1)
        
print(arr_2d_copy)

我正在尝试获得这样的输出 -

array([[ 2,  9, 10],
       [ 3, 12, 15],
       [ 6, 16, 22],
       [10, 21, 30]])

由于索引错误,我的代码显然无法正常工作。

python arrays sorting
1个回答
0
投票

您在遍历数组的同时删除条目,从而减少数组大小。

为了避免这种情况,请创建一个列表,您将在其中存储要删除的索引,并在循环后将其删除。

arr_2d = np.array([[ 1,  2,  4,  9, 3, 10],
                   [ 1,  3,  4, 12, 3, 15],
                   [ 1,  6,  4, 16, 3, 22],
                   [ 1, 10,  4, 21, 3, 30]])
arr_2d_copy = arr_2d.copy()
indices_to_delete = []
for col_idx in range(arr_2d.shape[1]):
    are_all_same = np.all(arr_2d[:,col_idx] == arr_2d[:,col_idx][0])
    print('Same? ', are_all_same)
    if are_all_same:
        indices_to_delete.append(col_idx)

arr_2d_copy = np.delete(arr_2d_copy, indices_to_delete, axis=1)
        
print(arr_2d_copy)
© www.soinside.com 2019 - 2024. All rights reserved.