• [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
    

      

  • 相关阅读:
    再来五道剑指offer题目
    高强度学习训练第十天总结:Class文件
    windows linux 子系统及windows terminal的使用。
    从植物大战僵尸开始一步一步带你入门逆向工程,
    高强度学习训练第九天总结:5道剑指offer的题目
    高强度学习训练第八天总结:MySQL的一些优化
    JVM的一些工具的简要使用
    手把手教你使用Java实现一个神经网络
    指定路径创建文件,并写入数据
    c#创建windows服务(代码方式安装、启动、停止、卸载服务)
  • 原文地址:https://www.cnblogs.com/KennyRom/p/6693954.html
Copyright © 2020-2023  润新知