用Python将大数据写入文件的最快方法

2024-09-29 01:26:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个大的数组(10^8 x 5)。我希望能写这个数据文件在其他程序中使用。在

按照this StackOverflow answer中的建议,我只使用numpy.savetxt写入磁盘一次,而不是重复调用write()。但是,考虑到我的数据大小,这既慢又产生非常大的文件(约47gb)。在

我知道我可以使用numpy.save之类的东西,但我希望能够用Fortran读取输出文件。它不一定是人类可读的。在

最佳选择/最佳实践?在

谢谢

一些示例代码:

    import numpy as np
    from scipy.interpolate import interpld as interpld

    #Load the data
    data = np.loadtxt('path/to/file/file.txt')

    #Extract the data - let's just say it is x,y,z coordinates
    x = data[:,0]
    y = data[:,1]
    z = data[:,2]

    # Do some interpolation to increase the 'resolution' of xyz coordinates

    baseline = np.zeros(len(x))
    for k in range(len(baseline)):
        baseline[k] = k

    N = 10000 # set resolution relative to baseline
    IntBaseline = np.linspace(0,baseline[-1],len(baseline)*N)


    gx = interpld(baseline,x)
    gy = interpld(baseline,y)
    gz = interpld(baseline,z)

    interpolated_x = gx(IntBaseline)
    interpolated_y = gy(IntBaseline)
    interpolated_z = gz(IntBaseline)


    # Now write everything to an array and save

    outfile = np.zeros((len(interpolated_x),3)
    outfile[:,0] = interpolated_x
    outfile[:,1] = interpolated_y
    outfile[:,2] = interpolated_z

    np.savetxt('Interpolated_Outfile.txt', outfile)

Tags: 文件thetonumpydatalensavenp