numpy库的实现

简单随机抽样

indexs=[numpy.random.randint(len(data)) for _ in range(k) ]
data[indexs]#data需要是narray类型

按不同概率抽样

numpy.random.choice(a,size=None,replace=None,p=None)

该函数可以根据不同的概率进行有放回和无放回抽样,这里的p需要满足sum( p )=1

np.random.choice([1,2,3],size=(6,1),replace=True,p=[0.1,0.3,0.6])
# array([[2],
#        [2],
#        [2],
#        [2],
#        [3],
#        [3]])
Parameters
-----------
a : 1-D array-like or intIf an ndarray, a random sample is generated from its elements.If an int, the random sample is generated as if a were np.arange(a)
size : int or tuple of ints, optionalOutput shape.  If the given shape is, e.g., ``(m, n, k)``, then``m * n * k`` samples are drawn.  Default is None, in which case asingle value is returned.
replace : boolean, optionalWhether the sample is with or without replacement
p : 1-D array-like, optionalThe probabilities associated with each entry in a.If not given the sample assumes a uniform distribution over allentries in a.Returns
--------
samples : single item or ndarrayThe generated random samplesRaises
-------
ValueErrorIf a is an int and less than zero, if a or p are not 1-dimensional,if a is an array-like of size 0, if p is not a vector ofprobabilities, if a and p have different lengths, or ifreplace=False and the sample size is greater than the populationsize

pandas库的实现

 pandas.DataFrame.sample(n=None,frac=None,replace=False,weights=None,random_state=None,axis=None)

该函数主要针对DataFrame,可以进行纵向和横向的抽样,这里的weights只需要大于零就可以了

df=pd.DataFrame({'x':[1,2,3],'w':[9,5,3]})
df.sample(n=2,frac=None,replace=False,weights=df.w,random_state=1,axis=0)
# Out[65]:
#    x  w
# 0  1  9
# 1  2  5
Parameters
----------
n : int, optionalNumber of items from axis to return. Cannot be used with `frac`.Default = 1 if `frac` = None.
frac : float, optional(抽样的比例)Fraction of axis items to return. Cannot be used with `n`.
replace : boolean, optionalSample with or without replacement. Default = False.
weights : str or ndarray-like, optionalDefault 'None' results in equal probability weighting.If passed a Series, will align with target object on index. Indexvalues in weights not found in sampled object will be ignored andindex values in sampled object not in weights will be assignedweights of zero.If called on a DataFrame, will accept the name of a columnwhen axis = 0.Unless weights are a Series, weights must be same length as axisbeing sampled.If weights do not sum to 1, they will be normalized to sum to 1.Missing values in the weights column will be treated as zero.inf and -inf values not allowed.
random_state : int or numpy.random.RandomState, optionalSeed for the random number generator (if int), or numpy RandomStateobject.
axis : int or string, optionalAxis to sample. Accepts axis number or name. Default is stat axisfor given data type (0 for Series and DataFrames, 1 for Panels).Returns
-------
A new object of same type as caller.

random库的实现

无放回等概率抽样

 random.sample(population,k)

该函数实现了无放回等概率样本抽样,例子:

random.sample([1,2,3],2)
Chooses k unique random elements from a population sequence or set.Returns a new list containing elements from the population while
leaving the original population unchanged.  The resulting list is
in selection order so that all sub-slices will also be valid random
samples.  This allows raffle winners (the sample) to be partitioned
into grand prize and second place winners (the subslices).Members of the population need not be hashable or unique.  If the
population contains repeats, then each occurrence is a possible
selection in the sample.To choose a sample in a range of integers, use range as an argument.
This is especially fast and space efficient for sampling from a
large population:   sample(range(10000000), 60)

参考:

  1. pandas.DataFrame.sample的官方文件:
    https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sample.html

2.https://blog.csdn.net/qq_41080850/article/details/87906590?depth_1-

python中实现简单抽样的函数相关推荐

  1. python平方数迭代器_对python中的高效迭代器函数详解

    python中内置的库中有个itertools,可以满足我们在编程中绝大多数需要迭代的场合,当然也可以自己造轮子,但是有现成的好用的轮子不妨也学习一下,看哪个用的顺手~ 首先还是要先import一下: ...

  2. python函数分几种_简单了解Python中的几种函数

    python是支持多种范型的语言,可以进行所谓函数式编程,其突出体现在有这么几个函数: filter.map.reduce.lambda.yield lambda lambda函数的使用方法:在lam ...

  3. Python中str()与repr()函数的区别——repr() 的输出追求明确性,除了对象内容,还需要展示出对象的数据类型信息,适合开发和调试阶段使用...

    Python中str()与repr()函数的区别 from:https://www.jianshu.com/p/2a41315ca47e 在 Python 中要将某一类型的变量或者常量转换为字符串对象 ...

  4. python中的高阶函数

    python中的高阶函数 文章目录: 1 什么是高阶函数? 1.1 高阶函数:一个函数的`函数名`作为参数传给另外一个函数 1.2 高阶函数:一个函数返回值(return)为另外一个`函数` 2 py ...

  5. Python编程语言学习:python中与数字相关的函数(取整等)、案例应用之详细攻略

    Python编程语言学习:python中与数字相关的函数(取整等).案例应用之详细攻略 目录 python中与数字相关的函数 1.对小数进行向上取整 1.1.利用numpy库 1.2.利用math库

  6. Python中字符串常用处理函数

    ** Python中字符串常用处理函数 ** 1.len( )函数 用len( )函数计算字符串的长度 2.strip( )函数 删除字符串两边的空白符(包括:'\n'.'\t'.'\r') 注:只能 ...

  7. 【Python】Python中str()和repr()函数的区别

    作用 在 Python 中要将某一类型的变量或者常量转换为字符串对象通常有两种方法,即 str() 或者 repr() . 区别与使用 参考文章:Python 中 str() 和 repr() 函数的 ...

  8. python中比较重要的几个函数_Python 几个重要的内置函数 python中的内置函数和关键字需要背过吗...

    python重要的几个内置函数用法 python内置函数什么用忘不掉的是回忆,继续的是生活,错过的,就当是路过吧.来来往往身边出现很多人,总有一个位置,一直没有变.看看温暖的阳光,偶尔还是会想一想. ...

  9. python items函数用法,Python中dictionary items()系列函数的用法实例

    本文实例讲述了Python中dictionary items()系列函数的用法,对Python程序设计有很好的参考借鉴价值.具体分析如下: 先来看一个示例: import html # availab ...

  10. python enumerate函数_关于python中enumerate和zip函数的用法及举例

    关于python中enumerate和zip函数的用法及举例 关于enumerate函数: enumerate函数可以同时返回列表或元组等可迭代对象的下标和内容,但实际上,enumerate函数实际返 ...

最新文章

  1. 只用静态图像,就能实时渲染出丝滑3D效果 | CVPR 2021 Oral
  2. HDU 3058 Generator [AC自动机+期望DP]
  3. MapReduce示例——WordCount(统计单词)
  4. 最明的int和Integer的区别
  5. Coolite(二)服务器端Alert,Confirm,Prompt
  6. 关于python文件问题
  7. Angular 如何使用 InjectionToken 的方式得到当前 location 信息
  8. 【CF1338C】Perfect Triples【位运算】【构造】
  9. 怎么把网页保存到本地计算机,在IE浏览器中,将网页保存到本地计算机中,若只需保存其中的文字、超链接和表格信息,应该选择的保存类型为( )...
  10. python生成指定长度的列表_如何在python中创建固定大小列表?
  11. 力扣35-搜索插入位置(C++,左右闭区间,nums[mid]与target大小关系判断的不同及辨析)
  12. 高端的面试从来不会在HashMap的红黑树上纠缠太多
  13. [转] Official Microsoft Team Blogs / Microsoft Blogs
  14. 重复insmod同一个模块导致段错误
  15. 生产环境和开发环境_生产环境 VS 开发环境,关于Kubernetes的四大认识误区
  16. Java并发编程实战_《Java并发编程实战》PDF版本下载
  17. 豆丁当当免费下载神器
  18. C# ZipArchive 文件末端错误 的解决方案
  19. 计算机sci论文怎么写,计算机学院陈端兵教授分享SCI论文写作方法
  20. 阿里平头哥首次交货——玄铁910是个啥?是芯片吗?

热门文章

  1. python做正态分布的例子_python 绘制正态曲线的示例
  2. 2020年,生活从“不易”开始
  3. 高级会计职称计算机考什么,会计高级职称考哪些科目
  4. excel填充序列_分分钟搞定10万个序号自动填充,拒绝加班,你还在手动输入吗?...
  5. L08-Linux解决Device eth0 does not seem to be present,delaying initialization问题
  6. STM32+ADS1110
  7. C++实现cmd界面简单贪吃蛇游戏
  8. Unity3D陀螺仪的使用
  9. linux -----各种颜色代表什么
  10. case when 失效,看了这篇文章就明白了