Pandas:使用范围内的随机整数在df中创建新列

scr*_*Owl 50 python random integer range pandas

我有一个50k行的熊猫数据框.我正在尝试添加一个新列,它是从1到5的随机生成的整数.

如果我想要50k随机数我会使用:

df1['randNumCol'] = random.sample(xrange(50000), len(df1))
Run Code Online (Sandbox Code Playgroud)

但为此,我不知道该怎么做.

R中的旁注,我会这样做:

sample(1:5, 50000, replace = TRUE)
Run Code Online (Sandbox Code Playgroud)

有什么建议?

Mat*_*att 73

一种解决方案是使用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])
Run Code Online (Sandbox Code Playgroud)

为了使结果可重复,您可以设置种子np.random.seed(42).


smc*_*mci 14

要添加一列随机整数,请使用randint(low, high, size).没有必要浪费内存分配range(low, high); 如果high很大,可能会有很多内存.

df1['randNumCol'] = np.random.randint(0,5, size=len(df1))
Run Code Online (Sandbox Code Playgroud)

(另请注意,当我们只添加单个列时,size只是一个整数.一般来说,如果我们想生成一个数组/数据帧randint()s,size可以是一个元组,就像在Pandas中一样:如何创建一个随机数据帧整数?)