【问题标题】:I have a list of 1-D arrays. I want to dump it to a csv file with each row as the 1-D array. Is it possible to do it using numpy,save?我有一个一维数组的列表。我想将它转储到一个 csv 文件中,每行作为一维数组。是否可以使用 numpy,save 来做到这一点?
【发布时间】:2019-05-07 13:02:30
【问题描述】:

示例:f_1= [array([[1.1,2.2,3.7,4.9,5.2 ]], dtype=float32), 数组([[9,11.5,5.8,6.7,8.9]],dtype=float32)]

转储文件应该是 csv 文件,其中 row 是列表的元素(一维数组)。

【问题讨论】:

  • 查看ndarray.tofile,它允许您指定分隔符等。
  • np.save(file, np.array(f_1).squeeze())

标签: list csv numpy multidimensional-array dump


【解决方案1】:

由于两个数组具有相同的形状,所以很容易制作一个二维数组,并将其写入savetxt

In [491]: f_1= [np.array([[1.1,2.2,3.7,4.9,5.2 ]], dtype='float32'), np.array([[9,11.5,5.8,6.7,8.9]],dtype='float32')]

In [492]: f_1
Out[492]: 
[array([[1.1, 2.2, 3.7, 4.9, 5.2]], dtype=float32),
 array([[ 9. , 11.5,  5.8,  6.7,  8.9]], dtype=float32)]
In [493]: x = np.vstack(f_1)
In [494]: x
Out[494]: 
array([[ 1.1,  2.2,  3.7,  4.9,  5.2],
       [ 9. , 11.5,  5.8,  6.7,  8.9]], dtype=float32)
In [495]: x.shape
Out[495]: (2, 5)
In [496]: np.savetxt('test.txt', x,delimiter=',', fmt='%4.1f')
In [497]: cat test.txt
 1.1, 2.2, 3.7, 4.9, 5.2
 9.0,11.5, 5.8, 6.7, 8.9

【讨论】:

    猜你喜欢
    • 2020-06-05
    • 1970-01-01
    • 2019-04-16
    • 1970-01-01
    • 1970-01-01
    • 2017-12-06
    • 1970-01-01
    • 2020-10-08
    • 2019-06-09
    相关资源
    最近更新 更多