• python中numpy创建数组


    1. numpy数组的创建

    1.1 使用array方法进行创建

    数组是numpy中一种常见的格式,和列表类似,可以理解为矩阵,可以使用array方法进行获取

    import numpy as np
    import random
    
    #使用numpy生成数组,得到ndarray的类型
    t1 = np.array([1,2,3,])
    print(t1)
    print(type(t1))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    得到的结果就是数组形式
    在这里插入图片描述
    也可以不直接输入列表,而是配合range获得

    import numpy as np
    import random
    
    #使用numpy生成数组,得到ndarray的类型
    t2 = np.array(range(10))
    print(t2)
    print(type(t2))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    获得的结果与之前类似
    在这里插入图片描述

    1.2 使用arange方法进行创建

    除了array方法,还可以用arange方法生成

    import numpy as np
    import random
    
    t3 = np.arange(4,10,2)
    print(t3)
    print(type(t3))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    获得的结果其实是相同的
    在这里插入图片描述

    2. numpy中的数据格式

    在数组里,有多种数据格式,我们可以在创建数组时使用dtype参数来确定数据格式

    import numpy as np
    import random
    
    t4 = np.array(range(1,4),dtype="float")
    print(t4)
    print(t4.dtype)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    这样输出的数据格式就会是float64
    在这里插入图片描述
    如果一开始设置错了数据格式,后期也可以通过astype进行修改

    import numpy as np
    import random
    
    t4 = np.array(range(1,4),dtype="float")
    print(t4)
    print(t4.dtype)
    
    t5 = t4.astype("int8")
    print(t5)
    print(t5.dtype)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    这时候就能发现数据格式已经从float64变成了int8
    在这里插入图片描述

  • 相关阅读:
    基于SM2证书实现SSL通信
    mysql—各种函数的使用
    【无标题】
    数学知识——求组合数
    [go 面试] 一致性哈希:数据分片与负载均衡的黄金法则
    电工什么是电动势
    TiDB整体架构详解TiDB核心特性
    招投标系统软件源码,招投标全流程在线化管理
    C语言实现单链表
    Unity ProBuilder(自己创建斜面、拐角)
  • 原文地址:https://blog.csdn.net/weixin_44999258/article/details/128155517