如何存储多个具有不同长度的numpy 1d数组并打印 [英] How to store multiple numpy 1d arrays with different lengths and print it

查看:825
本文介绍了如何存储多个具有不同长度的numpy 1d数组并打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从循环中获得了几个numpy数组(X,),并希望存储它们.我知道我可以将它们附加到常规的python列表中

I got several numpy arrays (X, ) from a loop and would like to store them. I know that I could append them to a conventional python list

A = []
for i in range(10):
  A.append(some_numpy_array)

但是,此解决方案看起来并不美观,无法解析为numpy.savetxt.

However, this solution does not look elegant and cannot be parsed to numpy.savetxt.

numpy.savetxt("out.txt", A)

还有其他解决方法吗?

推荐答案

所以您有一个数组列表

In [6]: alist = [np.arange(i) for i in range(3,7)]
In [7]: alist
Out[7]: 
[array([0, 1, 2]),
 array([0, 1, 2, 3]),
 array([0, 1, 2, 3, 4]),
 array([0, 1, 2, 3, 4, 5])]

这有什么不雅之处?您可以将其包装在对象数组中

What's inelegant about that? You could wrap it in an object array

In [8]: arr=np.array(alist)
In [9]: arr
Out[9]: 
array([array([0, 1, 2]), array([0, 1, 2, 3]), array([0, 1, 2, 3, 4]),
       array([0, 1, 2, 3, 4, 5])], dtype=object)

这会丢失像append这样的列表方法,但是会得到像reshape这样的数组方法.数组数学必须求助于python级别的迭代,其速度相当于列表推导的速度.而且有一个大难题-所有子列表的长度都相同,结果是一个2d int数组,而不是一个对象.

That loses list methods like append, but gains array ones like reshape. And array math has to resort to the python level iteration, the speed equivalent of list comprehensions. And there's one big gotcha - It all the sublists have the same length, the result is a 2d int array, not an object one.

savetxt会像我一样将其转换为数组,然后尝试写入行". savetxt用于生成CSV输出-带有定界符的整齐的行和列.该显示对该列表没有意义,对吗?

savetxt, given a list, will turn it into an array as I did, and then try to write 'rows'. savetxt is designed to produced CSV output - neat rows and columns with delimiter. That display doesn't make sense with this list, does it?

In [11]: np.savetxt('test.txt',alist,fmt='%s',delimiter=',')
In [12]: cat test.txt
[0 1 2]
[0 1 2 3]
[0 1 2 3 4]
[0 1 2 3 4 5]

这将列表/数组写为一维数组,每行具有常规字符串格式.有效地

This wrote the list/array as a 1d array with general string formatting for each line. Effectively

In [13]: for row in alist:
    ...:     print(row)
    ...:     
[0 1 2]
[0 1 2 3]
[0 1 2 3 4]
[0 1 2 3 4 5]

您可以在打开的文件上重复执行savetxt,一次写入一个数组:

You could do repeated savetxt on an open file, writing one array at a time:

In [18]: with open('test.txt','wb') as f:
    ...:     for row in alist:
    ...:         np.savetxt(f, [row], fmt='%5d',delimiter=',')      
In [19]: cat test.txt
    0,    1,    2
    0,    1,    2,    3
    0,    1,    2,    3,    4
    0,    1,    2,    3,    4,    5

当尝试编写3d数组或其他不适合简单2d数字数组模型的数组时,人们会遇到相同的问题.您不必使用savetxt将文本写入文件.普通Python具有足够的工具.

People run into the same issue when trying to write 3d arrays, or other arrays that don't fit the simple 2d numeric array model. You don't have to use savetxt to write text to a file. Plain Python has sufficient tools for that.

 

这篇关于如何存储多个具有不同长度的numpy 1d数组并打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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