# -*- coding: utf-8 -*-
import numpy
import pandas
data = pandas.read_csv(
'D:\\PDA\\4.9\\data.csv'
)
#设置随机种子
numpy.random.seed(seed=2)
#按照个数抽样
data.sample(n=10)
#按照百分比抽样
data.sample(frac=0.02)
#是否可放回抽样,
#replace=True,可放回,
#replace=False,不可放回
data.sample(n=10, replace=True)
#典型抽样,分层抽样
gbr = data.groupby("class")
gbr.groups
typicalNDict = {
1: 2,
2: 4,
3: 6
}#定义一个字典,从一班级中抽取2个人,二班级中抽取4个人,三班级中抽取6个人
def typicalSampling(group, typicalNDict):
name = group.name
n = typicalNDict[name]
return group.sample(n=n)
result = data.groupby(
'class', group_keys=False
).apply(typicalSampling, typicalNDict)#向量化运算的函数apply
typicalFracDict = {
1: 0.2,
2: 0.4,
3: 0.6
}#定义字典,按照百分比抽样
def typicalSampling(group, typicalFracDict):
name = group.name
frac = typicalFracDict[name]
return group.sample(frac=frac)
result = data.groupby(
'class', group_keys=False
).apply(typicalSampling, typicalFracDict)
idclassscore
3940145
45163
5354195
2526164
37381107
7071175
8586277
8182263
54552121
6869256
1314269
8687293
5758282
8485285
94952103
96972108
35362101
8990286
4546295
8081281
20212138
6566383
8384352
3435366
67387
7778377
8283354
55563126
1718358
6768393
1011389
2627364
61623103
8889389
6970396
01377
9091391
9192359
4849398
78348
5253362