matlabfread的python高效翻译

2024-03-28 18:45:01 发布

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

我需要将matlabfread翻译成python,特别是允许读取到2d数组,并在读取时跳过数据。 我想出了以下方法,但我想可能有更高效和“Python式”的方法(我绝不是程序员)。有什么建议吗?请注意,我无法读取整个文件,然后对数组进行子采样,因为要读取的文件太大。在

def FromFileSkip(fid, count=1, skip=0, dtype=np.float32):
    if np.ndim(count)==0:
        if skip>=0:
            data = np.zeros(count, dtype=dtype)
            k = 0
            while k<count:
                data[k] = np.fromfile(fid, count=1, dtype=dtype)
                fid.seek(skip, 1)
                k +=1
            return data
    elif np.ndim(count)==1:
        if skip>0:
            data = np.zeros(count, dtype=dtype)
            k = 0
            while k<count[1]:
                data[:,k] = np.fromfile(fid, count=count[0], dtype=dtype)
                fid.seek(skip, 1)
                k +=1
            return data
    else:
        raise ValueError('File can be read only into 1d or 2d arrays')

Tags: 文件方法dataifcountnpzerosseek
1条回答
网友
1楼 · 发布于 2024-03-28 18:45:01

这或多或少是你的,只是稍微干净一点。在

def fromfileskip(fid,shape,counts,skip,dtype):
  """
  fid    : file object,    Should be open binary file.
  shape  : tuple of ints,  This is the desired shape of each data block.
           For a 2d array with xdim,ydim = 3000,2000 and xdim = fastest 
           dimension, then shape = (2000,3000).
  counts : int, Number of times to read a data block.
  skip   : int, Number of bytes to skip between reads.
  dtype  : np.dtype object, Type of each binary element.
  """
  data = np.zeros((counts,)  + shape)
  for c in xrange(counts):
    block = np.fromfile(fid,dtype=np.float32,count=np.product(shape))
    data[c] = block.reshape(shape)
    fid.seek( fid.tell() + skip)

  return data

相关问题 更多 >