是否有 Python 等同于 R 的 sample() 函数?

Is there a Python equivalent to R's sample() function?

我想知道 Python 是否与 R 中的 sample() 函数等效。

sample() 函数使用替换或不替换从 x 的元素中获取指定大小的样本。

语法是:

sample(x, size, replace = FALSE, prob = NULL)

(更多信息here

我想 numpy.random.choice(a, size=None, replace=True, p=None) 可能就是您要找的。

p参数对应于sample()函数中的prob参数。

pandas (Python's closest analogue to R) there are the DataFrame.sample and Series.sample 方法中,它们都是在版本 0.16.1 中引入的。

例如:

>>> df = pd.DataFrame({'a': [1, 2, 3, 4, 5], 'b': [6, 7, 8, 9, 0]})
>>> df
   a  b
0  1  6
1  2  7
2  3  8
3  4  9
4  5  0

在不放回的情况下采样 3 行:

>>> df.sample(3)
   a  b
4  5  0
1  2  7
3  4  9

从第 'a' 列中抽取 4 行并进行替换,使用第 'b' 列作为选项的相应权重:

>>> df['a'].sample(4, replace=True, weights=df['b'])
3    4
0    1
0    1
2    3

这些方法几乎与 R 函数相同,允许您从 DataFrame/Series 中抽取特定数量的值 - 或部分值 - 有或没有替换。请注意,R 的 sample() 中的 prob 参数对应于 pandas 方法中的 weights

我相信 random 包有效。具体来说 random.sample().

here

这里的其他答案很好,但我想提一下 Scikit-Learn 的替代方案,我们也可以将其用于此,see this link

像这样:

resample(np.arange(1,100), n_samples=100, replace=True,random_state=2)

给你这个:

[41 16 73 23 44 83 76  8 35 50 96 76 86 48 64 32 91 21 38 40 68  5 43 52
 39 34 59 68 70 89 69 47 71 96 84 32 67 81 53 77 51  5 91 64 80 50 40 47
  9 51 16  9 18 23 74 58 91 63 84 97 44 33 27  9 77 11 41 35 61 10 71 87
 71 20 57 83  2 69 41 82 62 71 98 19 85 91 88 23 44 53 75 73 91 92 97 17
 56 22 44 94]