Python如何实现排列和随机采样排列?

2026-05-21 16:521阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计208个文字,预计阅读时间需要1分钟。

Python如何实现排列和随机采样排列?

Python 提供了 `random` 模块,其中的 `permutations` 函数用于生成排列,`sample` 函数用于随机采样。以下是修改后的开头和内容:

pythonPython 中使用 random 模块进行排列和随机采样。


Python如何实现排列和随机采样排列?

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)


本文共计208个文字,预计阅读时间需要1分钟。

Python如何实现排列和随机采样排列?

Python 提供了 `random` 模块,其中的 `permutations` 函数用于生成排列,`sample` 函数用于随机采样。以下是修改后的开头和内容:

pythonPython 中使用 random 模块进行排列和随机采样。


Python如何实现排列和随机采样排列?

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)