Python 保存一个 numpy 矩阵

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25749215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:35:19  来源:igfitidea点击:

Save a numpy matrix

pythonarraysnumpymatrix

提问by CatarinaCM

I have a 3D array and I would like to obtain a 2D image along X-Y with the maximum value of z at each point and save it as a numpy array.

我有一个 3D 数组,我想沿 XY 获取一个 2D 图像,每个点的 z 值都最大值,并将其保存为一个 numpy 数组。

import numpy as num
matrix=num.load('3d')
nx,ny,nz=num.shape(matrix)
CXY=num.zeros([ny, nx])
    for i in range(ny):
        for j in range(nx):
            CXY[i,j]=num.max(matrix[j,i,:])

The problem is to save the obtained matrix. I would like to save it with numpy.save but I always get an empty array. Does anyone have suggestions to properly save the obtained array?

问题是保存得到的矩阵。我想用 numpy.save 保存它,但我总是得到一个空数组。有没有人建议正确保存获得的数组?

I just used num.save:

我刚刚使用了 num.save:

num.save('max', CXY[i,j])

num.save('max', CXY[i,j])

采纳答案by Enfenion

I guess that you're looking for the numpy.savetxt which saves in a human readable format instead of the numpy.save which saves as a binary format.

我猜您正在寻找以人类可读格式保存的 numpy.savetxt 而不是以二进制格式保存的 numpy.save 。

import numpy as np
matrix=np.random.random((10,10,42))
nx,ny,nz=np.shape(matrix)
CXY=np.zeros([ny, nx])
for i in range(ny):
    for j in range(nx):
        CXY[i,j]=np.max(matrix[j,i,:])

#Binary data
np.save('maximums.npy', CXY)

#Human readable data
np.savetxt('maximums.txt', CXY)

This code saves the array first as a binary file and then as a file you can open in a regular text editor.

此代码首先将数组保存为二进制文件,然后保存为可以在常规文本编辑器中打开的文件。