# 8-Python 科学计算_numpy 篇

1、Python 科学计算介绍
2、Numpy 之 ndarray 对象
3、Numpy 之 ufunc 运算
4、Numpy 之 矩阵运算

# 1、Python 科学计算介绍

#### 二、Python 与科学计算

Python 语法简单易学
拥有numpy、scipy、matplotlib等库
跨平台，开源免费

numpy
scipy
pandas
matplotlib

# 2、numpy 之 ndarray 对象

#### 一、array()

``````import numpy as np

a =np.array([1,2,3,4])             #       array([1,2,3,4])
b =np.array((1,2,3,4))             #       array([1,2,3,4])
``````
``````c =np.array([[1,2,3],[2,3,4]])

c.dtpye                                                   #       dtype(“int64”)

c.shape                                                   #       (2,3)
``````
``````c =np.array([[1,2,3],[2,3,4]])

c.shape = -1,2
``````

``````n = c.reshape((2,3))

n[0][0] = 10

n

c
``````

n和c共享一个内存，当改变n中的数组元素的值时，c中也会相应地改变。

``````np.array(1,10,2)            #       array([1,3,5,7,9])

np.logspace(1,10,3)         #       在1到10中生成等比数列，3代表3个元素
``````
``````s ="hello"

np.fromstring(s,dtype= np.int8)  #       生成字符串每个元素的ascii值的数组

#       array([104, 101, 108, 108, 111], dtype=int8)， h的ascii值为104
``````
``````a= np.array([1,2,3])

a[0]                              #       1
a[1:2]                           #       array([2])
a[1]= 10

a                                #       array([1,10,3])
``````

#### 二、定义结构体数组

``````>>>person = np.dtype({'names':['name','age'],'formats':['S32','i']})
# ‘S32’—32字节字符串类型，’i’—int32

>>>person
dtype([('name','S32'), ('age', '<i4')])

>>> a =np.array([('zhang',12)],dtype = person)
>>> a
array([('zhang',12)],dtype=[('name', 'S32'), ('age','<i4')])

>>>a[0]
('zhang', 12)

>>>a[0][0]
'zhang'

>>>a[0][1]
12

>>>a[0]['name']
'zhang'

>>>a[0]['age']
12
``````

# 3、numpy 之ufunc 运算

``````>>>
x = np.arange(1,10,1)

>>> x
array([1, 2, 3, 4, 5, 6, 7, 8, 9])

>>> y = np.sin(x)                    #       计算x数组中每个元素的正弦值
>>> y
``````

``````>>> import numpy as np
>>> from time import time
>>> x = [i*0.001 for i in xrange(10000)]
>>> start = time()
>>> import math
>>> for i,t in enumerate(x):
x[i] = math.sin(t)

>>> print time() - start
190.217000008
``````
``````>>> x = [i*0.001 for i in xrange(10000)]
>>> x = np.array(x)
>>> start = time()
>>> np.sin(x,x)

>>> print time() - start

36.5990002155
``````

``````>>>x = np.array([1,2,3])
>>> y = np.array([3,2,4])

>>> x + y
array([4, 4, 7])

>>> x - y
array([-2,  0, -1])

>>> x * y
array([ 3,  4, 12])

>>> x / y

array([0, 1, 0])

>>> x ** y
array([ 1,  4, 81])
``````

``````import numpy as np

def func(x,c,c0,hc):
x = x - int(x)
if x >= c: r = 0.0
elif x < c0: r = x/c0*hc
else:
r = ((c-x)/(c-c0))*hc

return r

print func(1,0.6,0.4,1.0)                          #       0.0

print func(0.2,0.6,0.4,1.0)                      #       0.5

print func(0.4,0.6,0.4,1.0)                     #       1.0
``````
``````x = np.linspace(0,2,100)               #       生成一个0到2的100个元素的列表
y = np.array( [ func(t,0.6,0.4,1.0) for t in x] )

print y
``````
``````x =np.linspace(0,2,100)
funcs =np.frompyfunc(lambda x:func(x,0.6,0.4,1.0),1,1)

#两个1表示一个输入参数，一个为输出参数，是np.frompyfunc的参数

y = funcs(x)

print y
``````
``````def func(c,c0,hc):
def trifunc(x):
x = x - int(x)
if x >= c: r = 0.0
elif x < c0: r = x/c0*hc
else:
r = ((c-x)/(c-c0))*hc
return r

return np.frompyfunc(trifunc,1,1)            #       生成的是一个函数对象

x =np.linspace(0,2,100)
y =func(0.6,0.4,1.0)(x)

print y

# print y.astype(np.float64)
#  frompyfunc不能保证返回的内容数据类型一致
``````

# 4、numpy 之矩阵运算

``````>>> a =np.arange(12).reshape(2,3,2)

# arange使用和range的使用方法一样。reshape(2,2,3)转换成2个2行3列的矩阵
``````
``````>>> b =np.arange(12,24).reshape(2,2,3)

>>> c = np.dot(a,b)                                                         #       将a,b两个数组相乘
``````
``````b =np.arange(12,24).reshape(2,3,2)

>>> c =np.inner(a,b)                                             #       a,b两个数组的内乘
``````
``````>>> c =np.outer([1,2,3],[4,5,6])                         #       a,b 两个数组的外乘

>>> c
array([[ 4,  5,  6],
[ 8, 10, 12],
[12, 15, 18]])
``````