文章目录
04 Python科学计算:用NumPy快速处理数据
使用Numpy让你的Python科学计算更高效
-
避免采用隐式拷贝,而是采用就地操作的方式
可以提高计算速度 -
ndarray
NumPy数组中的维数称为秩(rank),一个线性的数组称为一个轴(axes),秩就是描述轴的数量。 -
创建数组
import numpy as np
a = np.arrary([1, 2, 3,])
b = np.array([1, 2, 3], [4, 5, 6], [7, 8, 9])
b[1, 1] = 10
print a.shape
print b.shape
print a.dtype
print b
运行结果
(3L,)
(3L, 3L)
int32
[[1 2 3]
[4 10 6]
[7 8 9]]
import numpy as np
persontype = np.dtpye({
'name':['name', 'age', 'chinese', 'math', 'english'],
'formats':['s32', 'i', 'i', 'i', 'f']} # 定义结构
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)
ages = peoples[:]['age']
chinese = peoples[:]['age']
maths = peoples[:]['chinese']
englishs = peoples[:]['english']
print np.mean(ages) # 求平均值
print np.mean(chinese)
print np.mean(maths)
print np.mean(englishs)
- ufunc运算
x1 = np.arange(1,11,2) # 创建等差数组:初始值,终值,步长
x2 = np.linspace(1,9,5) # 创建等差数组:初值、终值,元素个数
- 算法运算
x1 = np.arange(1,11,2)
x2 = np.linspace(1,9,5)
print np.add(x1, x2) # 加
print np.substact(x1, x2) # 减
print np.multiply(x1, x2) # 乘
print np.divide(x1, x2) # 除
print np.power(x1, x2) # 幂
print np.remainder(x1, x2) # 取余 np.remainder()与np.mod()一样
- 统计函数
'''
计算矩阵的最大最小值
'''
import numpy as np
a = np.array([