Python如何实现排列和随机采样排列?
- 内容介绍
- 文章标签
- 相关推荐
本文共计262个文字,预计阅读时间需要2分钟。
Python 提供了 `random` 模块中的 `permutations` 和 `sample` 函数来进行排列和随机抽样。
- `permutations` 函数用于生成一个列表的所有可能排列。- `sample` 函数用于从序列中随机选择指定数量的元素。
以下是一个简单的例子:
pythonimport random
排列示例numbers=[1, 2, 3]print(排列:, random.permutations(numbers))
随机抽样示例print(随机抽样:, random.sample(numbers, 2))
python排列和随机采样permutation&sample
### Permutation and Random Sampling# 排列和随机采样
# 利⽤numpy.random.permutation函数可以轻松实现对Series或
# DataFrame的列的排列⼯作(permuting,随机重排序)。通过
# 需要排列的轴的⻓度调⽤permutation,可产⽣⼀个表示新顺序
# 的整数数组:
df = pd.DataFrame(np.arange(5 * 4).reshape((5, 4)))
sampler = np.random.permutation(5)
sampler
array([2, 1, 3, 0, 4])
df
df.take(sampler)
df.sample(n=3)
choices = pd.Series([5, 7, -1, 6, 4])
draws = choices.sample(n=10, replace=True)
draws
choices = pd.Series([5, 7, -1, 6, 4])
draws = choices.sample(n=10, replace=True)
本文共计262个文字,预计阅读时间需要2分钟。
Python 提供了 `random` 模块中的 `permutations` 和 `sample` 函数来进行排列和随机抽样。
- `permutations` 函数用于生成一个列表的所有可能排列。- `sample` 函数用于从序列中随机选择指定数量的元素。
以下是一个简单的例子:
pythonimport random
排列示例numbers=[1, 2, 3]print(排列:, random.permutations(numbers))
随机抽样示例print(随机抽样:, random.sample(numbers, 2))
python排列和随机采样permutation&sample
### Permutation and Random Sampling# 排列和随机采样
# 利⽤numpy.random.permutation函数可以轻松实现对Series或
# DataFrame的列的排列⼯作(permuting,随机重排序)。通过
# 需要排列的轴的⻓度调⽤permutation,可产⽣⼀个表示新顺序
# 的整数数组:
df = pd.DataFrame(np.arange(5 * 4).reshape((5, 4)))
sampler = np.random.permutation(5)
sampler
array([2, 1, 3, 0, 4])
df
df.take(sampler)
df.sample(n=3)
choices = pd.Series([5, 7, -1, 6, 4])
draws = choices.sample(n=10, replace=True)
draws
choices = pd.Series([5, 7, -1, 6, 4])
draws = choices.sample(n=10, replace=True)

