首页 > 代码库 > [Python] Scipy and Numpy(1)
[Python] Scipy and Numpy(1)
import numpy as np #Create an array of 1*10^7 elements arr = np.arange(1e7) #Converting ndarray to list larr = arr.tolist() #Create a 2D numpy array arr = np.zeros((3,3)) #Converting a array to matrix mat = np.matrix(arr) np.matrix(‘1,2,3;4,5,6;7,8,9‘); #Array Creation #First we create a list and then #wrap it with the np.array() function alist = [1,2,3] arr = np.array(alist) #Creating an array of zeros with 5 elements arr = np.zeros(5) #Creating an array going from 0 to 100 #not include 100 arr = np.arange(100) #from 10 to 100 (not include 100) arr = np.arange(10, 100) #100 steps form 1 to 100 #(start, end, step) arr = np.linspace(0, 1, 100) #Creating an 5X5 array of zeros image = np.zeros((5,5)) #Creating a 5X5X5 cube of 1‘s #The astype() method sets the array with integer elements cube = np.zeros(5,5,5).astype(int) + 1 #Or even simpler with 16-bit floating-point precision cube = np.ones((5,5,5)).astype(np.float16) #Change Data type #Use dtype: int numpy.float16, numpy.float32, numpy.float64 arr = np.zeros(2, dtype=int) arr = np.zeros(2, dtype=np.float32) ‘‘‘ The restructured arrays are just different views of the same data in memory. If chang one of them, you will change all. If you don‘t want this to happen, then use the numpy.copy function to separete the arrays mamory-wise. ‘‘‘ #Created arrays and reshape them in many others ways #Creating an array with elements from 0 to 999 arr1d = np.arange(1000) #reshaping the array to a 10x10x10 3D array arr3d = arr1d.reshape((10,10,10)) arr3d = np.reshape(arr1d, (10,10,10)) #Invesely, we can flatten arrays arr4d = np.zeros((10,10,10,10)) arr1d = arr4d.ravel() print arr1d.shape recarr = np.zeros((2,), dtype(‘i4, f4, a10‘)) #the type for the first to third columns #i4 := 32-bit integer #f4 := 32-bit float #a10 := a string 10 characters long #We can assign names to each column recarr.dtype.names = (‘Integers‘, ‘Floats‘, ‘Strings‘) #Indexing and Slicing alist = [[1,2],[3,4]] arr = np.array(alist) arr[0,1]#It‘s the same as arr[0][1] arr[:,1]#return the last column arr[1,:]#return the bottom row
[Python] Scipy and Numpy(1)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。