Python数据分析与展示:ndarray多维数组的存储与读取-2

csv文件

np.savetxt()
np.loadtxt()

多维数组

a.tofile()
np.fromfile()
np.save()
np.savez()
np.load()

代码实例

# -*- coding: utf-8 -*-

# @File    : csv_demo.py
# @Date    : 2018-05-06

import numpy as np

# 存贮和读取1维或2维数组
def foo1():
    a = np.arange(100).reshape((20, 5))

    # 写入文件
    np.savetxt(fname="data.csv", X=a, fmt="%d",delimiter=",")

    # 读取文件
    b = np.loadtxt(fname="data.csv", dtype=np.int, delimiter=",")
    print(b)

# 写入读取多维数组,数组结构会丢失
def foo2():
    # 可以将数据结构存入一个文件,读取
    a = np.arange(100).reshape((10, 5, 2))

    # 写入文件
    a.tofile(file="data.dat", sep=",", format="%s")

    # 读取文件
    b = (np.fromfile(file="data.dat", dtype=np.int, count=-1, sep=",")
            .reshape((10, 5, 2)))
    print(b)

# 便捷的存取读出npy文件
def foo3():
    a = np.arange(100).reshape((10, 5, 2))

    # 存储
    np.save(file="data.npy", arr=a)

    # 读取
    b= np.load(file="data.npy")
    print(b)

猜你喜欢

转载自blog.csdn.net/mouday/article/details/80216681
今日推荐