0

Lets say I have the following array:

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

How do I remove duplicates from each element in the array e.g.

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

So here there are two 3s, and I want one of those to be deleted, how can I perform such an action?

  • Welcome to SO. What have you tried? Did you find out how to do it for an array with one dimension? Maybe it's possible to extend that solution. Show us your effort, please :) Maybe you could also add what should happen to the deleted entries (`np.array`s won't have rows of differing length). – David Wierichs Jun 28 '20 at 21:06
  • 1
    Hi thanks for answering, I have tried doing it for one dimension and it worked just fine. I have also made sure to add a new number each time there is something deleted to maintain the same length as before. The problem is that nothing gets deleted every time I run the program. Further more I should mention that there isn't any syntax errors it just buggs and keeps running endlessly. – George Avrabos Jun 28 '20 at 21:22
  • Please show us the code that you have so far. Do you want to allow for duplicates in *different* rows? Because in that case you could just apply your one-dim. code on the rows. [This question](https://stackoverflow.com/questions/26958233/numpy-row-wise-unique-elements) might also help (looks like a dupe to me). – David Wierichs Jun 28 '20 at 21:28

1 Answers1

0

Given your example, it seems that you don't want repetition relatively to rows. You may be interested in numpy.random.choice and try something like this:

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)

Output:

% python3 script.py
[[7 4 6 3 1]
 [2 8 6 4 3]]
bousof
  • 1,241
  • 11
  • 13