Skip to content

数组方法

python
%pylab
Using matplotlib backend: Qt4Agg
Populating the interactive namespace from numpy and matplotlib

求和

python
a = array([[1,2,3], 
           [4,5,6]])

求所有元素的和:

python
sum(a)
21

指定求和的维度:

沿着第一维求和:

python
sum(a, axis=0)
array([5, 7, 9])

沿着第二维求和:

python
sum(a, axis=1)
array([ 6, 15])

沿着最后一维求和:

python
sum(a, axis=-1)
array([ 6, 15])

或者使用 sum 方法:

python
a.sum()
21
python
a.sum(axis=0)
array([5, 7, 9])
python
a.sum(axis=-1)
array([ 6, 15])

求积

求所有元素的乘积:

python
a.prod()
720

或者使用函数形式:

python
prod(a, axis=0)
array([ 4, 10, 18])

求最大最小值

python
from numpy.random import rand
a = rand(3, 4)
%precision 3
a
array([[ 0.444,  0.06 ,  0.668,  0.02 ],
       [ 0.793,  0.302,  0.81 ,  0.381],
       [ 0.296,  0.182,  0.345,  0.686]])

全局最小:

python
a.min()
0.020

沿着某个轴的最小:

python
a.min(axis=0)
array([ 0.296,  0.06 ,  0.345,  0.02 ])

全局最大:

python
a.max()
0.810

沿着某个轴的最大:

python
a.max(axis=-1)
array([ 0.668,  0.81 ,  0.686])

最大最小值的位置

使用 argmin, argmax 方法:

python
a.argmin()
3
python
a.argmin(axis=0)
array([2, 0, 2, 0], dtype=int64)

均值

可以使用 mean 方法:

python
a = array([[1,2,3],[4,5,6]])
python
a.mean()
3.500
python
a.mean(axis=-1)
array([ 2.,  5.])

也可以使用 mean 函数:

python
mean(a)
3.500

还可以使用 average 函数:

python
average(a, axis = 0)
array([ 2.5,  3.5,  4.5])

average 函数还支持加权平均:

python
average(a, axis = 0, weights=[1,2])
array([ 3.,  4.,  5.])

标准差

std 方法计算标准差:

python
a.std(axis=1)
array([ 0.816,  0.816])

var 方法计算方差:

python
a.var(axis=1)
array([ 0.667,  0.667])

或者使用函数:

python
var(a, axis=1)
array([ 0.667,  0.667])
python
std(a, axis=1)
array([ 0.816,  0.816])

clip 方法

将数值限制在某个范围:

python
a
array([[1, 2, 3],
       [4, 5, 6]])
python
a.clip(3,5)
array([[3, 3, 3],
       [4, 5, 5]])

小于3的变成3,大于5的变成5。

ptp 方法

计算最大值和最小值之差:

python
a.ptp(axis=1)
array([2, 2])
python
a.ptp()
5

round 方法

近似,默认到整数:

python
a = array([1.35, 2.5, 1.5])

这里,.5的近似规则为近似到偶数值,可以参考:

https://en.wikipedia.org/wiki/Rounding#Round_half_to_odd

python
a.round()
array([ 1.,  2.,  2.])

近似到一位小数:

python
a.round(decimals=1)
array([ 1.4,  2.5,  1.5])

© 2023-2024 LiuJingcheng. 保留所有权利。