1.pd.DataFrame.sample
pd.DataFrame.sample(n=None, frac=None, replace=False, weights=None, random_state=None, axis=None)
描述
对数据集进行随机抽样,从对象轴返回随机的样本,您可以使用random_state进行再现
参数
n : int, optional
从对应轴要抽取的行数,不能与frac一起使用,如果frac = None,则默认= 1
frac : float, optional
从对应轴抽取行的比例,不能与n连用
replace : bool, default False
是否为有放回抽样;True:有放回抽样,False:未放回抽样
weights : str or ndarray-like, optional
字符索引或概率数组
axis=0:为行字符索引或概率数组
axis=1:为列字符索引或概率数组
random_state : int, array-like, BitGenerator, np.random.RandomState, optional
随机数发生器种子
axis : {0 or ‘index’, 1 or ‘columns’, None}, default None
选择抽取数据的行还是列,默认抽取行
axis=0:表示抽取行
axis=1:表示抽取列
返回值
Series or DataFrame
返回选择的n行或n列元素的Series or DataFrame对象
2.官方案例
从df[‘num_legs’]序列中提取3个随机元素:注意,我们使用random_state来确保示例的再现性
frac>1时,replace=True
采用列作为weights时,该列中较大的值可能更容易被采样