0

I have a list of numbers:

data = [15, 30, 45]

how to generate a list of N numbers taken randomly from this data list? To get result as:

new_data = [15,15, 30, 45, 15,45, 30, 15, 45, 30, 45, 45, 45, 15, ...]

np.random.randint(15, high=45, size=N) # does not help here

What numpy functions to use for this?

dokondr
  • 3,389
  • 12
  • 38
  • 62

4 Answers4

1

numpy.random.choice can do this:

import numpy

data = [15, 30, 45]
N = 20
new_data = numpy.random.choice(data, N)
print(new_data)

https://ideone.com/ECqtJ3

Fred Larson
  • 60,987
  • 18
  • 112
  • 174
1

You can simply use np.random.choice:

import numpy as np 
data=[15,30,45]
N = 50
new_list = np.random.choice(data,N)

Edit: Using random.sample() won't work as the sampling is done without replacement, therefore samples can't exceed length of the original data.

Celius Stingher
  • 17,835
  • 6
  • 23
  • 53
1

For a non-Numpy solution:

import random


l = [15, 30, 45]
N = 30
result = [random.choice(l) for i in range(N)]

# outputs: [15, 30, 15, 45, 15, 15, 30, 15, 30, 45, 15, 45, 30, 15, 30, 15, 15, 45, 30, 45, 30, 45, 45, 15, 15, 45, 30, 45, 45, 45]
revliscano
  • 2,227
  • 2
  • 12
  • 21
0
import random

data = [15, 30, 45]
new_data = []
N = 14

for i in range (0, N) :
    new_data.append(random.choice(data))

print("Data: ", data)
print("\nNew data :", new_data)

input("\n\nPress Enter to continue...")

https://ideone.com/5iD9U7

Anton Vrdoljak
  • 126
  • 1
  • 1
  • 5