zoukankan      html  css  js  c++  java
  • tofile和fromfile数组内建函数

    numpy教程:基本输入输出和文件输入输出Input and output

    使用数组的方法函数tofile可以方便地将数组中数据以二进制的格式写进文件。tofile输出的数据没有格式,因此用numpy.fromfile读回来的时候需要自己格式化数据

    >>> a = np.arange(0,12)
    >>> a.shape = 3,4
    >>> a
    array([[ 0,  1,  2,  3],
           [ 4,  5,  6,  7],
           [ 8,  9, 10, 11]])
    >>> a.tofile("a.bin")
    >>> b = np.fromfile("a.bin", dtype=np.float) # 按照float类型读入数据
    >>> b # 读入的数据是错误的
    array([  2.12199579e-314,   6.36598737e-314,   1.06099790e-313,
             1.48539705e-313,   1.90979621e-313,   2.33419537e-313])
    >>> a.dtype # 查看a的dtype
    dtype('int32')
    >>> b = np.fromfile("a.bin", dtype=np.int32) # 按照int32类型读入数据
    >>> b # 数据是一维的
    array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
    >>> b.shape = 3, 4 # 按照a的shape修改b的shape
    >>> b
    array([[ 0,  1,  2,  3],
           [ 4,  5,  6,  7],
           [ 8,  9, 10, 11]])

    Note:

    1. 读入的时候设置正确的dtype和shape才能保证数据一致。并且tofile函数不管数组的排列顺序是C语言格式的还是Fortran语言格式的,统一使用C语言格式输出。

    2. sep关键字参数:此外如果fromfile和tofile函数调用时指定了sep关键字参数的话,数组将以文本格式输入输出。{这样就可以通过notepad++打开查看, 不过数据是一行显示,不便于查看}

    user_item_mat.tofile(user_item_mat_filename, sep=' ')
  • 相关阅读:
    unity assert server 与 cache server
    Excel文件读写
    String与StringBuilder之间区别(转)
    c# 文件遍历
    C#整数三种强制类型转换int、Convert.ToInt32()、int.Parse()的区别
    2014年读过的书总结
    求职在年末
    被辞退于年末
    Unity Svn(转)
    公司的人员流动
  • 原文地址:https://www.cnblogs.com/TMatrix52/p/9669888.html
Copyright © 2011-2022 走看看