Pandas:使用范围内的随机整数在df中创建新列 [英] Pandas: create new column in df with random integers from range
本文介绍了Pandas:使用范围内的随机整数在df中创建新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个50k行的pandas数据框。我正在尝试添加一个新列,它是从1到5的随机生成的整数。
I have a pandas data frame with 50k rows. I'm trying to add a new column that is a randomly generated integer from 1 to 5.
如果我想要50k随机数我会使用:
If I want 50k random numbers I'd use:
df1['randNumCol'] = random.sample(xrange(50000), len(df1))
但为此我不知道该怎么做。
but for this I'm not sure how to do it.
旁注在R中,我会这样做:
Side note in R, I'd do:
sample(1:5, 50000, replace = TRUE)
有什么建议吗?
推荐答案
一种解决方案是使用 np .random.randint
:
One solution is to use np.random.randint
:
import numpy as np
df1['randNumCol'] = np.random.randint(1, 6, df1.shape[0])
# or if the numbers are non-consecutive (albeit slower)
df1['randNumCol'] = np.random.choice([1, 9, 20], df1.shape[0])
为了重新获得结果您可以使用 设置种子np.random.seed(42)
。
In order to make the results reproducible you can set the seed with np.random.seed(42)
.
这篇关于Pandas:使用范围内的随机整数在df中创建新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文