如何从具有多个维度的numpy数组中删除重复项

时间:2020-06-28 20:58:40

标签: arrays python-3.x numpy duplicates

让我们说我有以下数组:

board = np.random.randint(1, 9, size=(2, 5))

如何从数组中的每个元素中删除重复项 例如

[[6 1 2 8 4]
[8 3 2 3 6]]

所以这里有两个3,我想删除其中三个,我该如何执行这样的动作?

1 个答案:

答案 0 :(得分:0)

给出您的示例,看来您不希望相对于行重复。您可能对numpy.random.choice感兴趣,然后尝试执行以下操作:

import numpy as np

nb_lines = 2
nb_columns = 5
min_value = 1
max_value = 9
range_value = max_value-min_value

# The number of columns should be <= than the integer range to have a solution
assert(range_value+1 >= nb_columns)

board = min_value + np.array([
  np.random.choice(np.arange(range_value+1), nb_columns, replace=False)
  for l in range(nb_lines)
])

print(board)

输出:

% python3 script.py
[[7 4 6 3 1]
 [2 8 6 4 3]]
相关问题