安装方法
- 推荐使用.whl文件安装。我尝试了使用pip直接安装,虽然可以安装,但在
import scipy
时,出现ImportError: cannot import name NUMPY_MKL
,这是因为scipy依赖了numpy,numpy要安装numpy+mkl(Intel Math Kernel Library)。在安装scipy时出错,可以到http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy这个网页上下载。
numpy的一些用法
# 构建一个一维数组
a = numpy.array([0, 1, 2, 3, 4, 5])
print(a)
# 空间维数
print(a.ndim)
# 返回一个(列, 行)元组, 注意一维为(n, ), 一维以上为(n, m)
print(a.shape)
"""
>>>[0 1 2 3 4 5]
>>>1
>>>(6,)
"""
# 将一维矩阵转换成二维矩阵
a = numpy.array([0, 1, 2, 3, 4, 5])
b = a.reshape((3, 2))
print(b)
"""
[[0 1]
[2 3]
[4 5]]
"""
# numpy中也存在拷贝问题
a = numpy.array([0, 1, 2, 3, 4, 5])
b = a
b[0] = 2333
print(a)
print(b)
"""
[2333 1 2 3 4 5]
[2333 1 2 3 4 5]
"""
# 应该使用copy()函数
c = a.copy()
c[0] = 0
print(a)
print(b)
print(c)
"""
[2333 1 2 3 4 5]
[2333 1 2 3 4 5]
[0 1 2 3 4 5]
"""
a = numpy.array([0, 1, 2, 3, 4, 5])
b = a.copy()
# numpy中对数组的操作可以传递到每个元素上
print(b*2)
print(b)
"""
>>>[ 0 2 4 6 8 10]
>>>[0 1 2 3 4 5]
"""
# 利用这一点,可以用来修剪异常值
a[a > 4] = 4
print(a)
"""
>>>[0 1 2 3 4 4]
"""
# 或者利用clip(a, b)函数,将不再(a, b)范围内的数更改为b
print(b.clip(0, 4))
"""
>>>[0 1 2 3 4 4]
"""
# 处理不存在的值
a = numpy.array([0, 1, 2, 3, numpy.NAN, 4, 5])
print(a)
print(numpy.isnan(a))
print(a[~numpy.isnan(a)]) # 去除nan值
print(numpy.mean(~numpy.isnan(a))) # 计算平均值
"""
>>>[ 0. 1. 2. 3. nan 4. 5.]
>>>[False False False False True False False]
>>>[ 0. 1. 2. 3. 4. 5.]
>>>0.857142857143
"""
使用三种方法计算0到1000的平方和所花费时间
import timeit
s1 = timeit.timeit(stmt='sum(x*x for x in range(1000))',
number=1000)
s2 = timeit.timeit(stmt='sum(a*a)',
setup='import numpy; a=numpy.arange(1000)',
number=1000)
s3 = timeit.timeit(stmt='a.dot(a).sum()',
setup='import numpy; a=numpy.arange(1000)',
number=1000)
print(s1)
print(s2)
print(s3)
"""
>>>0.24655170031639762
>>>0.2955362870355932
>>>0.007861582461743177
"""
更多详细的用法参考:
- https://docs.scipy.org/doc/numpy/reference/
- https://docs.scipy.org/doc/numpy/user/