码迷,mamicode.com
首页 > 编程语言 > 详细

利用python进行数据分析-04-numpy基础

时间:2015-10-27 22:07:05      阅读:387      评论:0      收藏:0      [点我收藏+]

标签:

1、线性代数

矩阵乘法  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)

利用python进行数据分析-04-numpy基础

标签:

原文地址:http://www.cnblogs.com/groupe/p/4915062.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!