import numpy as np
import pandas as pd
from pandas import Series,DataFrame
一、随机重排列
df = DataFrame({'水果':['苹果','梨','草莓'],
'价格':[7,8,9],
'数量':[3,4,5]})
print(df)
价格 数量 水果
0 7 3 苹果
1 8 4 梨
2 9 5 草莓
1.permutation:产生0到n-1的所有整数的随机排列
sampler = np.random.permutation(3)
sampler
array([2, 0, 1])
2.行随机排列
print(df.take(sampler))
价格 数量 水果
2 9 5 草莓
0 7 3 苹果
1 8 4 梨
3.列随机排列
print(df.take(sampler,axis=1))
水果 价格 数量
0 苹果 7 3
1 梨 8 4
2 草莓 9 5
二、随机采样
1.方法一:sampler和take
sampler = np.random.randint(0,3,size=10)
sampler
array([1, 1, 2, 1, 0, 1, 1, 1, 2, 1])
print(df.take(sampler))
价格 数量 水果
1 8 4 梨
1 8 4 梨
2 9 5 草莓
1 8 4 梨
0 7 3 苹果
1 8 4 梨
1 8 4 梨
1 8 4 梨
2 9 5 草莓
1 8 4 梨
2.方法二:sample
df = pd.DataFrame(np.random.randn(50, 4), columns=list('ABCD'))
print(df.sample(n=3))
A B C D
46 -0.326369 1.191733 0.236718 -1.431329
45 0.368650 0.842136 -0.377916 0.803630
11 0.200736 -0.947885 0.534033 0.063705
print(df.sample(frac=0.1, replace=True))
A B C D
21 -1.393670 0.975525 0.898628 -0.555626
6 0.193062 0.972656 0.363302 0.647708
0 -0.538436 0.100367 0.194239 -0.782900
39 1.446714 0.535496 -0.264152 -1.819099
1 1.532854 -1.903245 0.689802 0.789996