Python Numpy(1)

来源:互联网 发布:网络教育文凭价格 编辑:程序博客网 时间:2024/06/04 18:21

1. # Five different way to create a vector

import numpy as np

# From a Python list 

vec1=np.array([0. , 1. ,2. ,3. ,4. ])

# arange ( start inclusive ,stop exclusive, step size)

vec2=np.arange(0,5,1,dtype=float)

#linspace( start inclusive ,stop inclusive ,number of elements)

vec3=np.linspace(0,4,5)

#zero(n) returns a vector filled with n zeros

vec4=np.zeos(5)

for i in range(5)

 vec4[i]=i;

#read from a text file, one number per row

vec5=np.loadtxt("data")


2. #contiuation from previous lists

#add a vector to another 

v1=vec1+vec2

#add a vector to another in place

vec1+=vec2


#Ufuncs: applying a function to a vector ,element by element

v5=np.sin(vec5)

#Calculating kernel density estimates

from numpy import *

#z :position ,w:bandwidth ,xv: vector of points

def kde(z,w,xv)

      return sum( exp(-0.5*((z-xv)/w)**2)/sqrt(2*pi*w**2) )

d= loadtxt("name",usecols=(2,))

w =2.5

for x in linspace (min(d)-w, max(d)+w,1000)

    print x, kde(x,w,d)


import numpy as np 


#generate two vector with 12 elements each

d1=np.linspace(0,11,12)

d2=np.linspace(0,11,12)


#Reshape the first vector to a 3*4 matrix

d1.shape=(3,4)

print d1


#Generate a matrix view to the second vector

view=d2.reshape((3,4))



4. access elements of an array

import numpy as np

#create a vector and reshape into matrix

d=np.linspace(0,11,12)

d.shape=(3,4)

#slicing

#First row

print d[0,:]

#second col

print d[:,1]


#individual element

print d[0,1]

#subvector of shape 1

print d[0:1,1]

#subarray of shape1*1

print d[0:1,1:2]    


#Index整体指向第一,第三列

print d[:,[2,0])


#Boolean index :指向第二,第三行

k=np.array([False ,True,True])

print d[k,:]





0 0
原创粉丝点击