利用python进行数据分析-04-numpy基础
1、线性代数
argmax()
函数y=f(x),x0= argmax(f(x)) 的意思就是参数x0满足f(x0)为f(x)的最大值;换句话说就是 argmax(f(x))是使得 f(x)取得最大值所对应的变量x。
any(x) 方法
def any(iterable): for element in iterable: if element: return False return True 参数iterable:可迭代对象;
如果iterable的任何元素不为0、''、False,all(iterable)返回True。如果iterable为空,返回False。
>>> any(['a', 'b', 'c', 'd']) #列表list,元素都不为空或0 True >>> any(['a', 'b', '', 'd']) #列表list,存在一个为空的元素 True >>> any([0, '', False]) #列表list,元素全为0,'',false False >>> any(('a', 'b', 'c', 'd')) #元组tuple,元素都不为空或0 True >>> any(('a', 'b', '', 'd')) #元组tuple,存在一个为空的元素 True >>> any((0, '', False)) #元组tuple,元素全为0,'',false False >>> any([]) # 空列表 False >>> any(()) # 空元组 False
all()方法
如果iterable的所有元素不为0、''、False或者iterable为空,all(iterable)返回True,否则返回False;函数等价于:
1
2
3
4
5
|
def all (iterable): for element in iterable: if not element: return False return True |
参数iterable:可迭代对象;
>>>
all
([
'a'
,
'b'
,
'c'
,
'd'
])
#列表list,元素都不为空或0
True
>>>
all
([
'a'
,
'b'
, '
', '
d'])
#列表list,存在一个为空的元素
False
>>>
all
([
0
,
1
,
2
,
3
])
#列表list,存在一个为0的元素
False
>>>
all
((
'a'
,
'b'
,
'c'
,
'd'
))
#元组tuple,元素都不为空或0
True
>>>
all
((
'a'
,
'b'
, '
', '
d'))
#元组tuple,存在一个为空的元素
False
>>>
all
((
0
,
1
,
2
,
3
))
#元组tuple,存在一个为0的元素
False
>>>
all
([])
# 空列表
True
>>>
all
(())
# 空元组
True
矩阵乘法 dot 函数
x= np.array([[1,2,3],[4,5,6]]) y=np.array([[6,23],[-1,7],[8,9]]) x Out[16]: array([[1, 2, 3], [4, 5, 6]]) y Out[17]: array([[ 6, 23], [-1, 7], [ 8, 9]]) x.dot(y) Out[18]: array([[ 28, 64], [ 67, 181]])
一个二维数组跟一个大小合适的一维数组的矩阵点积运算之后将会得到一个一维数组。
np.dot(x,np.ones(3))
Out[19]: array([ 6., 15.])
numpy.linalg
from numpy.linalg import inv,qr x = np.random.randn(5,5) mat = x.T.dot(x) inv(mat) Out[24]: array([[ 183.76974989, -623.36361091, -583.49826184, -235.16948917, -181.68152874], [ -623.36361091, 2121.59301898, 1985.26883645, 799.39704159, 619.72162247], [ -583.49826184, 1985.26883645, 1858.87861876, 747.67011221, 578.69498867], [ -235.16948917, 799.39704159, 747.67011221, 301.90295918, 233.89701649], [ -181.68152874, 619.72162247, 578.69498867, 233.89701649, 182.77441114]])
2、随机数生成
numpy.random模块对python的内置函数random进行了补充
如 : normal函数 可以生成 4*4的样本数组:
samples = np.random.normal(size = (4,4)) samples Out[11]: array([[-1.22102285, 2.08688133, 1.15874399, 0.14342708], [-0.29772372, 0.36137871, 0.60243437, -0.09287792], [-0.49263459, 0.69445334, 1.02035894, -1.18263174], [-0.07184985, -1.11834445, 0.89547984, 0.0585053 ]])
3、范例
随机漫步1000:
nsteps = 1000 draws = np.random.randint(0,2,size = nsteps) steps = np.where(draws>0,1,-1) walk = steps.cumsum() walk.min()
一次模拟多个多个随机漫步。
nwalk = 5000 nsteps =1000 nwalks =5000 draws = np.random.randint(0,2,size = (nwalks,nsteps)) steps = np.where(draws > 0 ,1,-1) walks = steps.cumsum(1) walks Out[28]: array([[ 1, 2, 1, ..., 16, 15, 16], [ -1, 0, -1, ..., 22, 21, 22], [ -1, 0, 1, ..., -36, -35, -36], ..., [ -1, 0, 1, ..., -16, -17, -18], [ 1, 0, 1, ..., 12, 11, 10], [ -1, 0, -1, ..., -8, -9, -8]], dtype=int32)