NumPy基础功能索引

NumPy基础功能索引

NumPy作为Python中一个强大的库,合理的使用不仅可以美化代码,还可以减少循环,提高执行效率。这篇文章的目的就是做一个Numpy的启发性索引。参考图书: 利用Python进行数据分析

  • NumPy基础功能索引
    • ndarray: 一种多维数组对象
      • 创建ndarray
      • 数组和标量之间的运算
    • 调用函数
      • 将条件逻辑表述为数组运算
    • 用于数组的文件输入输出
    • 随机数

ndarray: 一种多维数组对象

创建ndarray

Numpy中新定义了一个数组对象(ndarray)。该对象可以通过np1.array(其他迭代类型)来定义。ndarray对象内建函数shape(查看对象形式),reshape(重建对象形式),dtype2(查看数据类型)

其他的ndarray创建方法如下
  • np.ones()
  • np.zeros()
  • np.empty()
  • np.arange()
  • np.eye()
In [1]: import numpy as np
In [2]: np.ones((3, 3))
Out[2]:array([[ 1.,  1.,  1.],
              [ 1.,  1.,  1.],
              [ 1.,  1.,  1.]])

数组和标量之间的运算

这里很重要,是numpy代替for循环的一个体现。
数组与标量,数组与同型数组之间的运算都是元素级的运算

In [5]: testarray = np.ones((2, 2))
In [6]: testarray*2
Out[6]: 

array([[ 2.,  2.],
       [ 2.,  2.]])
In [7]: testarray + testarray
Out[7]: 

array([[ 2.,  2.],
       [ 2.,  2.]])

调用函数

一元函数:

函数 说明
abs/fabs 绝对值
sqrt 开方
square 平方
exp e的x次方
log/log10/log2/log1p 对数,其中log1p是指log(1+x)
sign 符号
ceil 计算个元素的ceiling值,即大于等于该值的最小整数
floor floor值,即小于等于该值的最大整数
rint 四舍五入,保留dtype
modf 将数组的小树和证书部分以两个独立数组形式返回
isnan 返回一个表示是否为空的数组
isfinite/isinf 返回一个表示是否有限或是否无穷的数组
cos/cosh/sin/sinhtan/tanh/
arccos/arccosh/arcsin/arcsinh/arctan/arctanh
logical_not 计算个元素not x的真值。相当于 -arr

二元函数:

函数 说明
add 元素加
subtract 元素减
multiply 元素乘
divide/floor_divide 元素除/元素地板除3
power 对每一个元素,计算A的B次方
maximum/fmax 元素级最大值/抛弃NAN
minimum/fmin 元素级最小值/抛弃NAN
mod 元素级求模

数组统计方法

方法 说明
sum 求轴向和
mean 求期望
std/var 求标准差/求方差
min/max 求最小值/求最大值
argmin/argmax 求最小值索引/求最大值索引
cunsum 求累计
cunprod 求累积

将条件逻辑表述为数组运算

if:

In [22]: result = [(x if c else y) for x, y, c in zip(xarray, yarray, cond)]
In [23]: xarray = np.arange(5)
In [24]: yarray = np.arange(5)+10
In [25]: cond = np.array([True, False, True, True, False])
In [26]: result = [(x if c else y) for x, y, c in zip(xarray, yarray, cond)]
In [27]: result
Out[27]: 
[0, 11, 2, 3, 14]

where:

In [28]: result = np.where(cond, xarray, yarray)
In [29]: result
Out[29]: 
array([ 0, 11,  2,  3, 14])

用于数组的文件输入输出

保存 读取
np.save(‘path’, testarray) np.load(‘path.npy)
np.savez(‘path’, a=testarray1, b=testarray2) np.load(‘path.npz’)
np.savetxt(‘path’) np.loadtxt(‘path.txt’)

随机数

部分numpy.random函数

函数 说明
seed 确定随机数生成器的种子
permutation 返回一个序列的随机排列或返回一个随机排列的范围
shuffle 对一个序列就地随机排列
rand 产生均匀分布的样本值
randint 从给定的上下限范围内随机选取整数
randn 产生正态分布(均值为0,方差为1)的样本值
binomial 产生二项分布的样本值
normal 产生正态分布的样本值
beta 产生Beta分布的样本值
chisquare 插死你哼卡方分布的样本值
gamma 产生Gamma分布的样本值
uniform 产生再[0,1)中均匀分布的样本值
例1:
np.random.randn()经常被我用来创建测试DataFrame
In [1]: import pandas as pd

In [2]: import numpy as np

In [3]: pd.DataFrame(np.random.randn(3, 4), index=list('123'), columns=list('abcd'))
Out[3]:
          a         b         c         d
1 -1.653480 -1.309714 -0.647547  0.612910
2 -0.456685 -0.896083 -0.925626 -0.774381
3 -0.626343  0.928588  1.006751 -0.066363
例2:
np.random.randint()经常用来产生随机数(抽签)
In [4]: np.random.randint(3, 5)
Out[4]: 3
In [5]: np.random.randint(3, 100)
Out[5]: 48
In [6]: np.random.randint(3, 10, size=(3, 4))
Out[6]: array([[7, 7, 5, 9],
               [3, 7, 5, 7],
               [9, 5, 3, 9]])
例3:
np.random.normal()用来产生服从正态分布的随机数,有三个参数,依次为 locscalesize。分别表示正态分布的均值、方差和生成随机数的shape。
In [1]: import numpy as np

In [2]: np.random.normal()
Out[2]: -1.3004106794256696

In [3]: np.random.normal(loc=10, scale=1, size=(3,4))
Out[3]: 
array([[10.33944193, 10.05519234, 11.42222642, 10.72775738],
       [ 9.30701505, 11.18810188,  9.47168679, 10.25634846],
       [11.41716704, 10.27783005,  9.50031229,  8.7759825 ]])

  1. import numpy as np ↩
  2. pandas的两个对象也可以用这个方法 ↩
  3. 去掉余数 ↩

你可能感兴趣的:(Python)