Charlie Cai Charlie Cai - 22 days ago 4
Python Question

how to use numpy.random to generate a matrix of int number

as I have mentioned in title, I fail to make it happened in my code. Here is my code, I try to use the two methods, but eventually it still cannot work.

# using python 2.7.12
import pandas as pd
dates = pd.date_range('20141001', periods = 7)
import numpy as np
dates1 = pd.DataFrame(np.random.randn(7,3), index =dates, columns = list('ABC'))
print dates1
dates2 = pd.DataFrame(np.random.randint(0,100), index =dates, columns = list('ABC'))

Answer

To create a matrix of random integers, you would write

import numpy as np
x = np.random.randint(low=0,high=100,size=(7,3) )
print x

low is the minimum integer that can be drawn, and high is the maximum integer plus one that can be drawn (i.e. high=100 means the maximum integer that can be drawn is 99). size determines the shape of the numpy array that will be returned. The output of the above code (given the random seed used on my machine) is:

array([[15, 97,  2],
       [88,  3,  6],
       [64, 97, 13],
       [18, 44, 75],
       [ 4, 59, 10],
       [97, 83, 73],
       [97, 21, 28]])

You can then cast this into a pandas DataFrame as you were before:

import numpy as np
import pandas as pd 

dates2 =  pd.DataFrame(np.random.randint(low=0,high=100,size=(7,3)),\
          index =dates, columns = list('ABC'))
Comments