How to specify a random seed while using Python's numpy random choice?

不羁岁月 提交于 2020-05-15 02:07:03

问题


I have a list of four strings. Then in a Pandas dataframe I want to create a variable randomly selecting a value from this list and assign into each row. I am using numpy's random choice, but reading their documentation, there is no seed option. How can I specify the random seed to the random assignment so every time the random assignment will be the same?

service_code_options = ['899.59O', '12.42R', '13.59P', '204.68L']
df['SERVICE_CODE'] = [np.random.choice(service_code_options ) for i in df.index]

回答1:


You need define it before by numpy.random.seed, also list comprehension is not necessary, because is possible use numpy.random.choice with parameter size:

np.random.seed(123)

df = pd.DataFrame({'a':range(10)})

service_code_options = ['899.59O', '12.42R', '13.59P', '204.68L']
df['SERVICE_CODE'] = np.random.choice(service_code_options, size=len(df))
print (df)
   a SERVICE_CODE
0  0       13.59P
1  1       12.42R
2  2       13.59P
3  3       13.59P
4  4      899.59O
5  5       13.59P
6  6       13.59P
7  7       12.42R
8  8      204.68L
9  9       13.59P



回答2:


Documentation numpy.random.seed

np.random.seed(this_is_my_seed)

That could be an integer or a list of integers

np.random.seed(300)

Or

np.random.seed([3, 1415])

Example

np.random.seed([3, 1415])

service_code_options = ['899.59O', '12.42R', '13.59P', '204.68L']
np.random.choice(service_code_options, 3)

array(['899.59O', '204.68L', '13.59P'], dtype='<U7')

Notice that I passed a 3 to the choice function to specify the size of the array.

numpy.random.choice



来源:https://stackoverflow.com/questions/52991675/how-to-specify-a-random-seed-while-using-pythons-numpy-random-choice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!