通过比赛整理出的8条Numpy实用技巧【你知道如何频数统计和按某列进行排序么?】...

本文介绍了8个Numpy的实用技巧,包括:1. 使用np.bincount()统计频数;2. 利用np.r_[]/np.c_[()]连接对象;3. 使用np.concatenate()拼接数组;4. 随机数生成函数np.random.rand(), np.random.randint(), np.random.randn(), np.random.normal();5. 排序函数np.sort()和np.argsort();6. 多维数组展平np.flatten();7. 改变形状np.reshape();8. 构造全0/1数组np.zeros(), np.zeros_like(), np.ones()和np.ones_like()。这些技巧在数据处理和分析中非常有用。" 70195159,5653236,进程间通信详解:管道与消息队列,"['进程通信', '管道通信', '消息队列通信', '系统编程', '操作系统']

点击上方“潜心的Python小屋”关注我们,第一时间推送优质文章。

前言

大家好,我是潜心。最近被比赛折磨得不行,能不能苟进复赛,混件文化衫也两说。在此我把用到的一些Numpy方法进行下总结。

本文约2.5k字,预计阅读15分钟。

1. 统计频数---np.bincount()

bincount()方法:计算非负整数数组中每个值出现的次数。返回一个输入数组的桶装(binning)结果。

numpy.bincount(x, weights=None, minlength=0)

参数介绍:

  • x:1维的非负整数数组;

  • weights:与x相同维度的权重数组;

  • minlength:输出数组的最小桶数(bins);当行并未出现最大的值时,就可以指定该参数;

例:

>>> np.bincount([1,2,3,4,5,1,1,1,5,4])
array([0, 4, 1, 1, 2, 2])

>>> np.bincount([1,2,3,4,5,1,1,1,5,4], weights=[0.1,0.2,0.3,0.4,0.5,0.1,0.2,0.3,0.4,0.5])
array([0. , 0.7, 0.2, 0.3, 0.9, 0.9])

>>> np.bincount([1], minlength=4)
array([0, 1, 0, 0])

2. 连接对象---np.r_[]/np.c_[]

np.r_[]/np.c_[]分别为沿行/列进行连接,这是一种快速构建数组的简单方法。数据挖掘中,最常用的就是为某个多维数组添加一行样本,或一列特征

例:

>>> np.r_[np.array([1,2,3]),  np.array([4,5,6])]
array([1, 2, 3, 4, 5, 6])

>>> np.c_[np.array([[1,2], [3,7], [8, 9]]),  np.array([4,5,6])]
array([[1, 2, 4],
       [3, 7, 5],
       [8, 9, 6]])

以上称为索引表达式。它的第一个元素放置的可选字符串可用于更改输出。字符串rc导致矩阵输出。如果结果是一维的,并且指定r,则生成一个1 x N矩阵。如果结果是一维的,并且指定了c,那么将生成一个N x 1矩阵。如果结果是二维的,那么两者都提供相同的矩阵结果。【不常用】

例:

>>> np.r_['r', np.array([1,2,3]),  np.array([4,5,6])]
matrix([[1, 2, 3, 4, 5, 6]])

>>> np.r_['c', np.array([1,2,3]),  np.array([4,5,6])]
matrix([[1],
        [2],
        [3],
        [4],
        [5],
        [6]])

它的第一个元素也可以放置字符数组。【对于将多个向量拼接为二维数组时可以使用】

  • 当为1个数字时,则是指定拼接的轴;

  • 当为2个数字时,分别指定拼接的轴以及维度的大小;【常用】

例:

>>> np.r_['0, 2', np.array([1,2,3]),  np.array([4,5,6])] # dim>=2
array([[1, 2, 3],
       [4, 5, 6]])

>>> np.r_['1, 2', np.array([1,2,3]),  np.array([4,5,6])]
array([[1, 2, 3, 4, 5, 6]])

>>> np.c_['0, 2', np.array([1,2,3]),  np.array([4,5,6])]
array([[1],
       [2],
       [3],
       [4],
       [5],
       [6]])

>>> np.c_['1, 2', np.array([1,2,3]),  np.array([4,5,6])]
array([[1, 4],
       [2, 5],
       [3, 6]])

3. 拼接函数---np.concatenate()

上述方法是一个索引表达式,numpy中也有很多拼接的函数如np.hstacknp.vstack,最常用的就是np.concatenate(),它沿现有轴连接数组序列,相比上述方法,它一次能实现多个数组拼接,但如果实现矩阵中添加向量最好使用上述方法。

numpy.concatenate((a1, a2, ...), axis=0, out=None)

参数介绍:

  • (a1, a2, …):数组序列,数组必须具有相同的形状,除了与axis对应的维度(默认情况下是第一个维度)

  • axis:整数,指定拼接的轴;若为None,则是将其展平为向量

  • out:If provided, the destination to place the result. (官方文档解释,没太懂,所以不翻译了,该参数基本不用)

例:

>>> a = np.array([[1, 2],[3, 4]])
>>> b = np.array([[5, 6]])

>>> np.concatenate((a, b), axis=0)
array([[1, 2],
       [3, 4],
       [5, 6]])

>>> np.concatenate((a, b.T), axis=1)
array([[1, 2, 5],
       [3, 4, 6]])

>>> np.concatenate((a, b), axis=None) 
array([1, 2, 3, 4, 5, 6])

4. 随机生成---np.random

生成随机数的方法在数据挖掘中是必不可少的,在Numpy中,最常使用的有四种方法:np.random.rand()【返回一个0~1的均匀样本】、np.random.randint()【返回随机整数的均匀样本】、np.random.randn()【返回一个标准正态分布的样本】和np.random.normal()【返回一个标准正态分布的样本】。

np.random.rand()

返回一个给定形状的使用[0, 1)的均匀分布的数组。

numpy.random.rand(d0, d1, ..., dn)

参数介绍:

  • d0, d1, ..., dn:返回数组的维度,必须非负。若没有该参数,则返回单一随机值;

例:

>>> np.random.rand()
0.25226001538874854

>>> np.random.rand(2,2)
array([[0.5402714 , 0.66014644],
       [0.68663483, 0.78903064]])

np.random.randint()

返回从低(含)到高(不含)的随机整数。在半开区间从指定的dtype的离散均匀分布中返回随机整数,如果high为None(缺省值),则结果来自[0,low)。

numpy.random.randint(low, high=None, size=None, dtype=int)

参数介绍:

  • low:整数或整数数组,指定下界。若high=None,则为上界,即范围为[0, low);

  • high:整数或整数数组,指定上界(不取);

  • size:整数或为一个整数元组(tuple),即定义的输出形状,若为None,则返回一个单一随机值;

  • dtype:定义结果类型;

例:

>>> np.random.randint(5, size=(2, 2))
array([[0, 4],
       [2, 1]])

>>> np.random.randint(2, 3, size=5)
array([2, 2, 2, 2, 2])

np.random.randn()

标准正态分布中返回一个(或多个)样本。

numpy.random.randn(d0, d1, ..., dn)

参数介绍:

  • d0, d1, ..., dn:返回数组的维度,必须非负。若没有该参数,则返回单一随机值;

例:

>>> np.random.randn()
-0.801081759054076

>>> np.random.randn(2, 2)
array([[ 0.00428205,  0.51626724],
       [ 0.83932361, -1.18135824]])

numpy.random.normal()

从正态(高斯)分布中随机抽取样本,默认为标准正态分布。

高斯分布的概率密度公式为:

其中 为均值, 为标准差。Numpy中函数定义如下:

numpy.random.normal(loc=0.0, scale=1.0, size=None)

参数介绍:

  • loc:float,分布的平均值;

  • scale:float,分布的标准差,必须是非负数;

  • size:整数或元组,输出形状。为None返回单一随机值;

例:

>>> mu, sigma = 0, 0.1 # mean and standard deviation
>>> s = np.random.normal(mu, sigma, 1000)

>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, 30, density=True)
>>> plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) *
...                np.exp( - (bins - mu)**2 / (2 * sigma**2) ),
...          linewidth=2, color='r')
[<matplotlib.lines.Line2D object at 0x12466ecc0>]
>>> plt.show()

5、排序---np.sort()/np.argsort()

Numpy中排序函数分为两种,一种是返回排序后的数组np.sort(),另一种为返回排序后的索引数组np.argsort()。通常对一个向量进行排序,会用第一种。但我们有时会想对一个矩阵按照某一列进行排序,那就不能使用np.sort(),通常是获得排序后的索引np.argsort(),在对矩阵进行调整。

np.sort()

Numpy中排序操作,通用函数为np.sort(),它返回一个被排序的数组。【一般为向量时会使用到】

numpy.sort(a, axis=-1, kind=None, order=None)

参数介绍:

  • a:被排序的数组;

  • axis:指定排序的轴,默认值为-1,则按照最后一个轴;

  • kink:排序算法,默认为quicksort,另外还有:mergesortheapsortstable

  • order:字符串或字符串列表。a是一个定义了字段的数组时,这个参数指定首先比较哪个字段,然后比较哪个字段。

例:

>>> a = np.array(
  [[1,4],
   [3,1]])
>>> np.sort(a)
array([[1, 4],
       [1, 3]])

>>> np.sort(a, axis=0) 
array([[1, 1],
       [3, 4]])

>>> np.sort(a, axis=None)
array([1, 1, 3, 4])

np.argsort()

返回将对数组排序的索引。通过获得索引可以指定数组按某行/列进行排序

numpy.argsort(a, axis=-1, kind=None, order=None)

参数介绍:

  • a:排序数组;

  • axis:默认-1,即按最后一个轴排序;如果为None,则展平为向量;

  • kind:排序算法,默认为quicksort

  • order:同np.sort()

例:

>>> x = np.array([[0, 3], [2, 2], [4, -1]])

>>> np.argsort(x, axis=0)
array([[0, 2],
       [1, 1],
       [2, 0]])

# 按第二列进行升序排序
>>> x[np.argsort(x, axis=0)[:,1]]
array([[ 4, -1],
       [ 2,  2],
       [ 0,  3]])

# 按第二列进行降序排序,添加一个负号即可
>>> x[np.argsort(-x, axis=0)[:,1]]
array([[ 0,  3],
       [ 2,  2],
       [ 4, -1]])

6. 多维数组展平---np.flatten()

这是在数据挖掘中非常常用的方法,有时得到一个N*1矩阵,经常将其转化为向量进行后续操作。类似方法还有ravel()

ndarray.flatten(order='C')

参数介绍:

  • order:{'C', 'F', 'A', 'K'},默认为C,以行进行展平;F以列进行展平;【最主要就是这两个】A means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise. K means to flatten a in the order the elements occur in memory.

例:

>>> a = np.array([[1,2], [3,4]])

>>> a.flatten()
array([1, 2, 3, 4])

>>> a.flatten('F')
array([1, 3, 2, 4])

7. 改变形状---np.reshape()

这个方法也经常用,主要用法是来改变维度(增删)。例如在黑白图像中,每张图片作为样本向神经网络中输入时需要增加一个维度,则需要np.reshape()

numpy.reshape(a, newshape, order='C')

参数介绍:

  • 改变形状的数组;

  • 整数或元组,新的形状。若元组最后一个数为-1,则表示最后一个维度是进行计算推断得出;

  • order:同np.flatten(),但无K;

>>> a = np.array([[1,2,3], [4,5,6]])

>>> np.reshape(a, 6)
array([1, 2, 3, 4, 5, 6])

>>> np.reshape(a, 6, order='F')
array([1, 4, 2, 5, 3, 6])

>>> np.reshape(a, -1)
array([1, 2, 3, 4, 5, 6])

8. 构造全0/1数组

构造全0/1的数组有时也会用到。

np.zeros()

返回填充为0的数组。

numpy.zeros(shape, dtype=float, order='C')

参数介绍:

  • shape:整数或元组,新数组的shape;

  • dtype:定义数组类型,默认为np.float64

  • order:同上,含CF

例:

>>> np.zeros(5)
array([0., 0., 0., 0., 0.])

>>> np.zeros((2, 2))
array([[0., 0.],
       [0., 0.]])

np.zeros_like()

返回与某数组类型相同维度的全零数组。

numpy.zeros_like(a, dtype=None, order='K', subok=True, shape=None

主要参数介绍:

  • a:所参照该形状的数组;

  • dtype:定义数组类型;

例:

>>> x = np.arange(6).reshape((2, 3))
>>> np.zeros_like(x)
array([[0, 0, 0],
       [0, 0, 0]])

np.ones()和np.ones_like()

同上述两种方法,区别就是填充为1,故不在重复介绍。

总结

只有实践,并总结,才会提高自己的工程能力。

阅读的朋友可以点个【在看】嘛,非常感谢!

参考文献

[1]. Numpy官方文档:https://numpy.org/devdocs/reference/

往期精彩回顾

竞赛知识积累---TF-IDF方法可以作为特征工程【sklearn实现】

Pandas笔记---深入Groupby,它的功能没有你想的这么简单

Pandas笔记---通过比赛整理出的10条Pandas实用技巧

机器学习笔记---你真的懂决策树么?

机器学习笔记---信息熵

扫码关注更多精彩

我就知道你“在看”

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值