I have an issue with random.sample function. Here is the code:
import random
import numpy as np
simulateData = np.random.normal(30, 2, 10000)
meanValues = np.zeros(1000)
for i in range(1000):
dRange = range(0, len(simulateData))
randIndex = np.random.sample(dRange, 30)
randIndex.sort()
rand = [simulateData[j] for j in randIndex]
meanValues[i] = rand.mean()
This is the error:
TypeError Traceback (most recent call last)
<ipython-input-368-92c8d9b7ecb0> in <module>()
20
21 dRange = range(0, len(simulateData))
---> 22 randIndex = np.random.sample(dRange, 30)
23 randIndex.sort()
24 rand = [simulateData[i] for i in randIndex]
mtrand.pyx in mtrand.RandomState.random_sample (numpy\random\mtrand\mtrand.c:10022)()
TypeError: random_sample() takes at most 1 positional argument (2 given)
I found several past references where such an error was supposedly addressed via changing import order like in my case above (random, before numpy). Supposedly random module gets overwritten somehow during the import while I can not imagine why would that be in a high level language. However in my case it did not work. I tried all possible variations but came with no solution
The problem in itself is an attempt to bootstrap: get random samples (equal size) from the initial distribution and measure the mean and std.
I am puzzled, especially since the solution which is supposed to work does not. I have Python 2.7
Please, help
I guess you are confusing random.sample
with np.random.sample()
-
np.random.sample(size=None)
- Return random floats in the half-open interval[0.0, 1.0)
.
size
: int or tuple of ints, optional Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.
random.sample(population, k)
- Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.
You are using np.random.sample
, but trying to pass it arguments as random.sample
. I think you want to use random.sample
, if so you should use it like -
randIndex = random.sample(dRange, 30)
You are trying to pass two arguments -- dRange
and 30
-- to the sample
function, but sample
only allows one argument. Here's some of the documentation where it says this:
random_sample(size=None)
Return random floats in the half-open interval [0.0, 1.0).
Parameters
----------
size : int or tuple of ints, optional
The order of your imports should not be a problem.
For taking 30 random samples from an array, maybe you want numpy.choice
instead:
np.random.choice(dRange, 30)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With