Generate alphanumeric random numbers in numpy

numpy random number
python random number
numpy random uniform
numpy random normal
numpy random seed
numpy random float
numpy random random
numpy random number generator example

I want random numbers 100000+, I found numpy is suitable for my project based on performance it is good. But I want 4 places random number based on below pattern,

'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'

In the above case 26 small letters,26 capital letters and 10 digits equal to 62 total letters and let us take permutation and combinations,

I want 4 digits from those letters so,

62 ^ 4 / 4! = 615680 (Combinations)

If I take 26 small letters + 10 digits and the output is,

(26+10) ^ 4 / 4! = 69984 (Combinations)

From those two cases first one is best, It provides better random numbers, I did some logic here,

from numpy.random.mtrand import RandomState
import binascii
lo = 1000000000000000
hi = 999999999999999999
In [65]: %timeit [ binascii.b2a_hex(rand.randint(lo, hi, 2).tostring())[:4] for _ in xrange(100000)]
1 loops, best of 3: 272 ms per loop

But the random number count is below 100000, Because it only takes small lettes + digits

In [66]: len(set([binascii.b2a_hex(rand.randint(lo, hi, 2).tostring())[:4] for _ in xrange(100000)]))
Out[66]: 51210

Any one suggest me how to implement this in numpy ?

As pointed out by NPE, you can use numpy.random.choice. Does this code achieve what you want?

import numpy as np

LENGTH = 4
NO_CODES = 100000

alphabet = list('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
np_alphabet = np.array(alphabet, dtype="|S1")
np_codes = np.random.choice(np_alphabet, [NO_CODES, LENGTH])
codes = ["".join(np_codes[i]) for i in range(len(np_codes))]

print(codes)

It takes a couple of seconds to execute with NO_CODES = 1000000 on my 2-years-old but not bad computer.

Random Generator, Generator exposes a number of methods for generating random numbers drawn from a dirichlet (alpha[, size]), Draw samples from the Dirichlet distribution. Generating random numbers with NumPy. array([-1.03175853, 1.2867365 , -0.23560103, -1.05225393]) Generate Four Random Numbers From The Uniform Distribution

It can be done much faster by using numpy view.

A, Z = np.array(["A","Z"]).view("int32") 

NO_CODES = 100
LEN = 20

np.random.randint(low=A,high=Z,size=NO_CODES*LEN,dtype="int32").view(f"U{LEN}")

Random sampling (numpy.random), random_integers (low[, high, size]), Random integers of type np.int between low and choice (a[, size, replace, p]), Generates a random sample from a given 1-D array dirichlet (alpha[, size]), Draw samples from the Dirichlet distribution. Related to these two methods, there is another method called normal([loc, scale, size]), using which we can generate random numbers from the normal distribution specified by loc and scale parameters. 3. randint (low[, high, size, dtype])

The accepted answer can be made a bit faster with the following code:

import numpy as np

length  = 4
n_codes = 100000
alpha_num = list('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')

np_codes = np.random.choice(alpha_num, size=[n_codes, length])
codes = [code.tostring() for code in np_codes]

Original runtime on my machine: 10 loops, best of 3: 204 ms per loop.

New runtime: 10 loops, best of 3: 27.6 ms per loop.

Python Generate a Random String and Password, Create a unique random string without repeating characters in it; Generate a random alphanumeric string with letters and numbers. Generate a  Produce a random alphanumeric string from the English alhpabet or any other alphabet of your choosing (custom input). The alphanumeric strings can be from any alphabet (German, French, Spanish, Russian, etc.). The random string generator can produce random alphanumeric strings of any required length and is helpful for randomly generating tokens for a raffle.

Neither of the other two answers worked for me, but I was able to use them to create the following solution:

import numpy as np

length  = 4
n_codes = 100000
alpha_num = list('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')

np_codes = np.random.choice(alpha_num, size=[n_codes, length])
codes = [''.join(code) for code in np_codes]

A Cheat Sheet on Generating Random Numbers in NumPy, Note that the numbers specified in the rand() function correspond to the number of dimensions of the array that is to be generated. A special case  38B453. Note: we can get a different number and alphabet as this Program generates any random number and alphabet. and numbers will range from 0 – 9 and alphabet will range from A – B, as all alphabet will be capital because we have specified that.

Random Generator, Generator exposes a number of methods for generating random numbers drawn from a variety of probability distributions. The Python stdlib module random contains pseudo-random number dirichlet (alpha[, size]). The secrets module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets. In particularly, secrets should be used in preference to the default pseudo-random number generator in the random module, which is designed for modelling and simulation, not security or cryptography.

Generating Random Data in Python (Guide) – Real Python, “True” random numbers can be generated by, you guessed it, a true random number generator (TRNG). One example is to repeatedly pick up a die off the floor,  I want to generate a string of size N. It should be made up of numbers and uppercase English letters such as: How can I achieve this in a pythonic way? This is a very popular question. I wish an expert would add his take on the uniqueness of these random numbers for the top 3 answers i.e. the collision probability for range of string size, say

Python Random Data Generation, rand() vs np.random.random()?; What is the difference between various numpy random functions? how to generate random integer values using  Random String Generator. This form allows you to generate random text strings. The randomness comes from atmospheric noise, which for many purposes is better than the pseudo-random number algorithms typically used in computer programs.

Comments
  • numpy.random.choice() 4-vectors from the alphabet, and then ''.join() each?
  • Or if you told us the actual problem you are trying to solve, we might be able to better help you.
  • @NPE thanks for reply, I am trying to generate the random numbers 100000 for every time. So I need to save every unique random number into nosql db. And what is the problem is I want 4 places random number . 62 letters gives more unique random numbers compare to 36 letters. So from above logic it takes 32 letters not 64 letters.
  • Typically people use base 64 for this, which is your alphabet and the character '+' and '/'. This makes everything easier as you are now just generating a random number and then doing a base 64 conversion against it.
  • @Claris perhaps you can post your comment as an answer...
  • Running this on python 3.5 gives me the error message sequence item 0: expected str instance, numpy.bytes_ found
  • Try changing dtype to dtype="|U1"