• 技术文章 >Python技术 >Python基础教程

    python中numpy数据类型转换的方法

    小P小P2020-10-30 10:46:10原创9424
    本篇文章主要讲述numpy转换astype,dtype的方法,具体代码展示如下:

    1、查看数据类型

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei";">In [11]: arr = np.array([1,2,3,4,5])

     

    In [12]: arr

    Out[12]: array([1, 2, 3, 4, 5])

     

    // 该命令查看数据类型

    In [13]: arr.dtype

    Out[13]: dtype('int64')

     

    In [14]: float_arr = arr.astype(np.float64)

     

    // 该命令查看数据类型

    In [15]: float_arr.dtype

    Out[15]: dtype('float64')<br></span></p>

    2、转换数据类型


    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei";">// 如果将浮点数转换为整数,则小数部分会被截断

    In [7]: arr2 = np.array([1.1, 2.2, 3.3, 4.4, 5.3221])

     

    In [8]: arr2

    Out[8]: array([ 1.1   ,  2.2   ,  3.3   ,  4.4   ,  5.3221])

     

    // 查看当前数据类型

    In [9]: arr2.dtype

    Out[9]: dtype('float64')

     

    // 转换数据类型  float -> int

    In [10]: arr2.astype(np.int32)

    Out[10]: array([1, 2, 3, 4, 5], dtype=int32)<br></span></p>

    3、字符串数组转换为数值型


    1

    2

    3

    4

    5

    6

    7

    8

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei";">In [4]: numeric_strings = np.array(['1.2','2.3','3.2141'], dtype=np.string_)

     

    In [5]: numeric_strings

    Out[5]: array(['1.2', '2.3', '3.2141'], dtype='|S6')

     

    // 此处写的是float 而不是np.float64, Numpy很聪明,会将python类型映射到等价的dtype上

    In [6]: numeric_strings.astype(float)

    Out[6]: array([ 1.2, 2.3, 3.2141])<br></span></p>


    numpy转换的方法还是很简单,小伙伴们快快动手尝试一下吧~更多Python学习推荐:PyThon学习网教学中心

    专题推荐:numpy数据类型转换方法;python
    上一篇:python之int与eval函数的区别 下一篇:Python基础:numpy中any()和all()的用法

    相关文章推荐

    • mongodb如何存numpy数组• pycharm如何安装numpy• pycharm如何导入numpy• 怎么在anaconda中升级numpy?• 安装anaconda后无法导入numpy怎么办• pycharm有numpy扩展包么• pycharm如何使用numpy

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网