如何在使用Python的numpy随机选择时指定随机种子? [英] How to specify a random seed while using Python's numpy random choice?
本文介绍了如何在使用Python的numpy随机选择时指定随机种子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有四个字符串的列表.然后在Pandas数据框中,我想创建一个变量,从该列表中随机选择一个值,并将其分配给每一行.我正在使用numpy的随机选择,但是阅读其文档时,没有任何种子选项.如何为随机分配指定随机种子,以便每次随机分配都相同?
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]
推荐答案
您需要先通过 numpy.random.choice
,参数为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
这篇关于如何在使用Python的numpy随机选择时指定随机种子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文