dtype 初始化定义

import numpy as np
persontype = np.dtype({
    'names':['name', 'age', 'chinese', 'math', 'english'],
    'formats':['S32','i', 'i', 'i', 'f']}) 
# S32 32位的字符串, U32 32位的unicode
peoples = np.array([("ZhangFei",32,75,100, 90),("GuanYu",24,85,96,88.5),
       ("ZhaoYun",28,85,92,96.5),("HuangZhong",29,65,85,100)],
    dtype=persontype)

运算函数

x1 = np.arange(1,11,2)
x2 = np.linspace(1,9,5)  # 结果等价 
print np.add(x1, x2)
print np.subtract(x1, x2)
print np.multiply(x1, x2) # 乘法
print np.divide(x1, x2)
print np.power(x1, x2)
print np.remainder(x1, x2) # 等价于 np.mod
"""
Output:
[ 2.  6. 10. 14. 18.]
[0. 0. 0. 0. 0.]
[ 1.  9. 25. 49. 81.]
[1. 1. 1. 1. 1.]
[1.00000000e+00 2.70000000e+01 3.12500000e+03 8.23543000e+05
 3.87420489e+08]
[0. 0. 0. 0. 0.]
"""

计算数组/矩阵中的最大值函数 amax(), 最小值函数 amin()

import numpy as np
a = np.array([[1,2,3], [4,5,6], [7,8,9]])
print np.amin(a)
print np.amin(a,0) # 沿着 y 轴, axis=0
print np.amin(a,1) # 沿着 x 轴, axis=1
print np.amax(a)
print np.amax(a,0)
print np.amax(a,1)
"""
Output:
1
[1 2 3]
[1 4 7]
9
[7 8 9]
[3 6 9]
"""

统计最大值和最小值之差

a = np.array([[1,2,3], [4,5,6], [7,8,9]])
print np.ptp(a)
print np.ptp(a,0)
print np.ptp(a,1)
"""
Output:
8
[6 6 6]
[2 2 2]
"""

统计数组的百分位数 percentile()

a = np.array([[1,2,3], [4,5,6], [7,8,9]])
print np.percentile(a, 50)
print np.percentile(a, 50, axis=0)
print np.percentile(a, 50, axis=1)
"""
Output:
5.0
[4. 5. 6.]
[2. 5. 8.]
"""

percentile() 代表着第 p 个百分位数,这里 p 的取值范围是 0-100,如果 p=0,那么就是求最小值,如果 p=50 就是求平均值,如果 p=100 就是求最大值。同样你也可以求得在 axis=0 和 axis=1 两个轴上的 p% 的百分位数。

统计数组中的中位数 median(), 平均数 mean()

a = np.array([[1,2,3], [4,5,6], [7,8,9]])
# 求中位数
print np.median(a)
print np.median(a, axis=0)
print np.median(a, axis=1)
# 求平均数
print np.mean(a)
print np.mean(a, axis=0)
print np.mean(a, axis=1)
"""
Output:
5.0
[4. 5. 6.]
[2. 5. 8.]
5.0
[4. 5. 6.]
[2. 5. 8.]
"""