美文网首页我爱编程
numpy数组基础操作

numpy数组基础操作

作者: abc渐行渐远 | 来源:发表于2017-11-15 18:21 被阅读0次
    #coding:utf-8
    import numpy as np
    if __name__ == '__main__':
    
        #创建数组
        x1 = np.random.randint(10, size=6)
        x2 = np.random.randint(10,size=(3,4))
        x3 = np.arange(10)
    
        '''
        #数组的属性
        print x2.ndim   #几维
        print x2.shape  #多少行列
        print x2.size   #元素个数
        print x2.dtype  #元素值类型
    
        #元素索引
        print x1
        print x1[1]
        print x1[-1] #最后一个
        print x2
        print x2[2,-1] #第3行最后一列
        print x3[3:-1]
        print x3[3:-1:2]
        print x3[::-1]
    
        #数组copy
        x2_t = x2.copy() #都copy
        x2_t = x2[1].copy() #copy一行
        print x2_t
    
    
        #数组重塑 (将一维的变为2维或3维。。。)
        print x3.reshape(2,5)
        print x3.reshape(len(x3), 1)
        print x3.reshape(-1,1)  #和上面的效果是一样的,变成1维的
    
        print x3[np.newaxis,3:10] #变成 [[3 4 5 6 7 8 9]]
        print x3[8:10,np.newaxis] #变成[[8][9]]
    
        #数组拼接(np.concatenate())
        x = np.array([1,2,3])
        y = np.array([4,5,6])
        print np.concatenate([x,y]) #concatenate 连接起来的意思
        x = np.array([[1,2,3],[4,5,6]])
        y = np.array([[11,12,13],[14,15,16]])
        print np.concatenate([x,y]) #二维数组的拼接, 列数必须一样, 接在行后
        print np.concatenate([x,y],axis=1) #接在列后
    
    
        #数组堆砌 stack  横向v  纵向h
        x = np.array([1, 2, 3])
        y = np.array([[4,5,6],[7,8,9]])
        print np.vstack([y, x])
        y = np.array([4,5,6])
        print np.hstack([x,y])
    
    
        #数组分割 split  横纵分割 v h
        x = [1,2,3,4,5,6] #一维数组的split
        a,b,c = np.split(x, [3,5]) #分别在下标3前分割,5分割, 形成3个数组
    
        x = np.arange(16).reshape(4,4)#二维的split
        a, b = np.vsplit(x, [2]) #在下标2行前分割成两个二维数组
        print x
        print a
        print b
        a, b = np.hsplit(x,[2]) #第2列前分割
        print a
        print b
        '''
    
    

    相关文章

      网友评论

        本文标题:numpy数组基础操作

        本文链接:https://www.haomeiwen.com/subject/dvyhvxtx.html