-2

There is a numpy array like following numpy array. I want to generate a random integer number for specific string of the numpy array.. How can I do this task?

# input
X = np.array([['a', 'p', 'b'],
              ['a', 'p', 'd'],
              ['c', 'p', 'd'],
              ['c', 'p', 'e'],
              ['c', 'p', 'f']])

# output
X = np.array([[100, 5, 101],
              [100, 5, 103],
              [102, 5, 103],
              [102, 5, 104],
              [102, 5, 105]])
Md. Rezwanul Haque
  • 2,882
  • 7
  • 28
  • 45

1 Answers1

1

As you want to assign a random integer values for each unique value of the array, you can map the unique values to a dictionary.

Update

We need to create check if the random number is used as a value of the mapper.

from random import randint
import numpy as np


# input
X = np.array([['a', 'p', 'b'],
              ['a', 'p', 'd'],
              ['c', 'p', 'd'],
              ['c', 'p', 'e'],
              ['c', 'p', 'f']])

mapper = {}

output = []
for ar in X:
    temp = []
    for i in range(len(ar)):
        if ar[i] not in mapper:
            random_number = None
            while True:
                random_number = randint(1,120)
                if random_number not in mapper.values():
                    break
            mapper[ar[i]] = random_number
        temp.append(mapper[ar[i]])
    output.append(temp)
output = np.array(output)
print(output)

Output:

[[  7  86 120]
 [  7  86  14]
 [ 51  86  14]
 [ 51  86 113]
 [ 51  86  54]]
arshovon
  • 13,270
  • 9
  • 51
  • 69