numpy 简单使用

numpy get started

  • 导入numpy库,并查numpy版本

    In [1]: import numpy  as np
    In [2]: np.__version__
          '1.14.0'
    

一、创建ndarray

  • 1.使用np.array()由python list 创建

    In [1]: list1 = [1,2,3,4,5]
    	    nparray1 = np.array(list1)
    In [2]: nparray1
    Out [2]: array([1, 2, 3, 4, 5])
    In [3]: list1
    Out [2]: [1,2,3,4,5]
    
    In [1]:list3 = [1,2,3,4,5]
    	   # numpy提供了各种数据类型的表达方式
           arr3 = np.array(object=list3, dtype=np.float32)
           arr3
    Out [1]:array([1, 2, 3, 4, 5])
    
      In[1]:# 构建一个高维数组
            list4 = [[1,2,3],[4,5,6]]
            arr4 = np.array(list4)
            arr4	
      Out[2]:array([[1, 2, 3],
             [4, 5, 6]])
    
    注意:
    
    numpy默认ndarray的所有元素的类型是相同的
    如果传进来的列表中包含不同的类型,则统一为同一类型,优先级:str>float>int
    
  • 2.使用np的routines函数创建

      1. np.ones(shape, dtype=None, order=‘C’)
        In[1]:np.ones(shape=10)
        Out[1]:array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
        In[1]:np.ones(shape=(2,3))
        Out[1]:array([[1., 1., 1.],
        [1., 1., 1.]])
        In[1]:np.ones(shape=(2,3), dtype=np.int8)
        Out[1]:array([[1, 1, 1],
        [1, 1, 1]], dtype=int8)
      1. np.zeros(shape, dtype=float, order=‘C’)
        In[1]:np.zeros(shape=(3,3), dtype=np.int8)
        Out[1]:array([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]], dtype=int8)
      1. np.full(shape, fill_value, dtype=None, order=‘C’)
        In[1]:np.full(shape=(3,3), fill_value=5, dtype=np.int8)
        Out[1]:array([[5, 5, 5],
        [5, 5, 5],
        [5, 5, 5]], dtype=int8)
      1. np.eye(N, M=None, k=0, dtype=float) 对角线为1其他的位置为0
        In[1]:np.eye(N=3,M=5,k=-1)
        Out[1]:array([[0., 0., 0., 0., 0.],
        [1., 0., 0., 0., 0.],
        [0., 1., 0., 0., 0.]])
      1. np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
        In[1]:# 生成一维的等差数列
        np.linspace(0,10,num=10,endpoint=False)
        Out[1]:array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])
      1. np.arange([start, ]stop, [step, ]dtype=None)
        In[1]:np.arange(0,10,1)
        Out[1]:array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
      1. np.random.randint(low, high=None, size
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值