使用np.savetxt和np.loadtxt用多维数组 [英] Using np.savetxt and np.loadtxt with multi-dimensional arrays

查看:5626
本文介绍了使用np.savetxt和np.loadtxt用多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是存储更比2维数组的通用方式( NDIM> 2 )到文件,并使用相同的格式(尺寸)检索它 np.savetxt np.loadtxt

What is a generalized way of storing a more-than-2 dimensional array (ndim > 2) to file and retrieving it in same format (dimension) using np.savetxt and np.loadtxt?

我担心的是,如果我给出任何分隔符,同时存储,我需要给一些治疗方法,同时获取?加上花车处理,并在相同的格式检索它是有点棘手。

My concern is if I give any delimiter while storing, do I need to give some treatments while retrieving? Plus dealing with floats and retrieving it in same format is little tricky.

我已经看到了很多文档简单的例子。我只是好奇,是否最简单的存储 np.savetxt(文件名,数组)可以用简单的 =阵列np.loadtxt(文件名)进行检索或没有。

I have seen many simple examples in the docs. I am just curious about whether the simplest storing np.savetxt(filename, array) can be retrieved using simply array = np.loadtxt(filename) or not.

推荐答案

如果您需要保存多维数组中的文本文件,你可以使用参数保存原始阵列形状:

If you need to save multi-dimensional arrays in a text file you can use the header parameter to save the original array shape:

import numpy as np

a = np.random.random((2, 3, 4, 5))

header = ','.join(map(str, a.shape))
np.savetxt('test.txt', a.reshape(-1, a.shape[-1]), header=header,
           delimiter=',')

和加载该阵列可以这样做:

And to load this array you can do:

with open('test.txt') as f:
    shape = map(int, f.next()[1:].split(','))
    b = np.genfromtxt(f, delimiter=',').reshape(shape)

这篇关于使用np.savetxt和np.loadtxt用多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆