How to draw random numbers with python to match in Pandas Dataframe

56 Views Asked by At

So I have my code which does work as it generated 6 numbers. However, I feel as though a loop of some kind would work better for two reasons.

First - to eliminate the repetitive code as it is written below and, second, to get my desired output as follows 12 24 63 2 55 3 INSTEAD of what is currently happening [12, 24, 63, 2, 55, 3]

Reason being is that information from a statistics pandas dataframe has the output as 12 24 63 2 55 3 without it being in a list and having commas.

rdmFirstNum = (random.randrange(1, 100))
rdmSecondNum = (random.randrange(1, 100))
rdmThirdNum = (random.randrange(1, 100))
rdmFourthNum = (random.randrange(1, 100))
rdmFifthNum = (random.randrange(1, 100))
rdmSixthNum = (random.randrange(1, 50))

rdmNums = [rdmFirstNum, rdmSecondNum, rdmThirdNum, rdmFourthNum, rdmFifthNum, rdmPwrNum]
print (rdmNums) 
3

There are 3 best solutions below

1
Nick On

You should generate your numbers in a loop, a list comprehension works well here:

rdmNums = [random.randrange(1, 100 if i < 5 else 50) for i in range(6)]

or possibly two joined comprehensions:

rdmNums = [random.randrange(1, 100) for _ in range(5)] + [random.randrange(1, 50) for _ in range(1)]

If you then print rdmNums you will get the string representation of a list e.g.:

[41, 71, 47, 4, 84, 20]

To print a space separated list of numbers, use map to convert them to strings and join:

print(' '.join(map(str, rdmNums)))

Output:

41 71 47 4 84 20
0
FlakkCatcher On

I tried to figure this out using just a while True loop and list concatenation:

import random
rdmNums = []
while True:
    rdmNum = (random.randrange(1, 100))
    if len(rdmNums) == 6:
        break
    rdmNums = rdmNums + [rdmNum]
for rdmNum in rdmNums:
    print(rdmNum)

It will print a list of 6 random numbers without printing them in a list format. However, it does print them one line at a time and if you want more/less numbers, you'd need to change the amount to break in the first if-statement.

0
mozway On

I would use 's np.random.randint with a list of your upper bounds:

import numpy as np

rdmNums = np.random.randint(1, [100, 100, 100, 100, 100, 50])
# array([ 1,  5, 90, 61, 65, 31])

print(*rdmNums)

# or
print(' '.join(rdmNums.astype(str)))

Example output:

1 5 90 61 65 31

If you have many times a boundary to repeat and don't want to type the list manually you can take advantage of repeat:

rdmNums = np.random.randint(1, np.repeat([100, 50], [5, 1]))

print(*rdmNums)