【问题标题】:How to save a large array in txt file in python如何在python的txt文件中保存一个大数组
【发布时间】:2017-12-31 21:29:32
【问题描述】:

我有二维数组:

import numpy as np

output = np.array([1,1,6])*np.arange(6)[:,None]+1

output
Out[32]: 
array([[ 1,  1,  1],
       [ 2,  2,  7],
       [ 3,  3, 13],
       [ 4,  4, 19],
       [ 5,  5, 25],
       [ 6,  6, 31]])

我尝试使用np.savetxt('file1.txt', output, fmt='%10d') 我只在一行中得到了结果

如何将其保存在 txt 文件中,类似于:

        x   y    z 
        1   1    1
        2   2    7
        3   3   13
        4   4   19
        5   5   25
        6   6   31

3 个独立的列,每列都有名称 (x,y,z)

请注意:原始数组太大(40000000行3列),我用的是Python 3.6 我已经尝试了herehere 中的解决方案,但是它不适用于我

【问题讨论】:

  • 这些解决方案在哪些方面失败了?
  • 40mio*3*3 个字符的数据和间距大约为 350mb,假设每个字符 1 个字节 - 这不是一个太大的文件。
  • @PatrickArtner:但是如果我们使用文本,它会使用分隔符(制表符和换行符),并且某些数据(例如浮点数)可以使用 ~10-20 位数字。
  • 大而不大
  • @WillemVanOnsem 当然,他的演示数据的整数范围在 99 以下,但我四舍五入;)只是想了解他的问题

标签: python arrays


【解决方案1】:

Noor,让我猜猜 - 你正在使用 Windows 记事本查看文件?

我使用 Notepad++,它足够聪明,可以理解np.savetxt() 创建文件时(默认情况下)使用的 Unix 风格的Lineendings,即使在 Windows 下操作也是如此。

您可能希望在调用savetxt 时明确指定newline="\r\n"

np.savetxt('file1.txt', output, fmt='%10d' ,header= "       x          y          z", newline="\r\n")

独库:https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.savetxt.html


我不确定你的数据,但是这个:

import numpy as np

output = np.array([1,1,6])*np.arange(60)[:,None]+1

print(output)


np.savetxt('file1.txt', output, fmt='%10d' ,header= "       x          y          z")

产生这个输出:

#        x          y          z
         1          1          1
         2          2          7
         3          3         13 
       === snipped a few lines ===
        58         58        343
        59         59        349
        60         60        355

对我来说。

  • 对于 np.arange(1000000),其大小约为 32MB,格式相似...

  • 对于 np.arange(10000000),它大约 322MB 大并且格式相似...

willem-van-onsem 1+Gb 更接近。

我没有考虑每个数字固定 10 个字符的间距,我的错。

【讨论】:

  • 谢谢,Patrick Artner,你是对的,Notepad++ 和 EmEditor,它们都以列和行的形式显示数组
  • @Noor - 指定使用的换行符和 windows 样式 - 这会为您的整体文件大小增加 40.000.000 字节;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-21
  • 1970-01-01
  • 2018-01-01
  • 2020-01-24
  • 2021-01-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多