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

Pandas: create new column in df with random integers from range

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

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

df1['randNumCol'] = random.sample(xrange(50000), len(df1))

但是我不知道该怎么做。

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

sample(1:5, 50000, replace = TRUE)

有什么建议吗?

一种解决方案是使用 numpy.random.randint:

import numpy as np
df1['randNumCol'] = np.random.randint(1, 6, df1.shape[0])

或者如果数字不连续(虽然速度较慢),您可以使用:

df1['randNumCol'] = np.random.choice([1, 9, 20], df1.shape[0])

为了使结果可重现,您可以使用 numpy.random.seed 设置种子(例如 np.random.seed(42)

要添加一列随机整数,请使用 randint(low, high, size)。无需浪费内存分配 range(low, high);如果 high 很大,那可能需要很多内存。

df1['randNumCol'] = np.random.randint(0,5, size=len(df1))

备注:

  • 当我们只添加一列时,size 只是一个整数。一般来说,如果我们想生成一个randint()s的array/dataframe,size可以是一个元组,如)
  • 使用 random.seed(...) 确定性和可重复性

不需要额外导入 numpy 的选项:

df1['randNumCol'] = pd.Series(range(1,6)).sample(int(5e4), replace=True).array