Python numpy.fromfile中的参数计数无效
这个问题可能很琐碎,但我真的不知道如何解决它。假设我使用类型Python numpy.fromfile中的参数计数无效,python,python-3.x,numpy,Python,Python 3.x,Numpy,这个问题可能很琐碎,但我真的不知道如何解决它。假设我使用类型np.int64生成一个大小为(4,3)的numpy数组,然后写入二进制文件。该数组如下所示: [[ 1 2 3] [ 4 5 6] [ 7 8 9] [10 11 12]] 现在,假设我的目标是只读取第二行,[4 5 6]。这应该使用默认函数工作。为此,我写了以下内容: import numpy as np import os # To write X = [[1, 2, 3], [4, 5, 6], [7, 8
np.int64
生成一个大小为(4,3)的numpy
数组,然后写入二进制文件。该数组如下所示:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
现在,假设我的目标是只读取第二行,[4 5 6]
。这应该使用默认函数工作。为此,我写了以下内容:
import numpy as np
import os
# To write
X = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
X = np.asarray(X, dtype=np.int64)
print("%s\n\n" % X)
X.astype(np.int64).tofile('test.dat')
# To read
f = open('test.dat', "rb")
n = 4
dim = 3
r = 1
f.seek((r*dim*8), os.SEEK_SET)
data = np.fromfile(f, count=(2*dim*8), dtype=np.int64).reshape(-1, dim)
print("The Reading data is:\n %s\n" % data)
但是,我得到了整个数组,尽管我只想要[4 5 6]
:
The Reading data is:
[[ 4 5 6]
[ 7 8 9]
[10 11 12]]
在np.fromfile
中,参数count=(r*dim*8)
似乎没有效果!!这是虫子吗?还是我做错了什么
谢谢如果您只想要
[4 5 6]
(1个元素,3个项目),您的计数应该是您的dim
(即3)
data = np.fromfile(f, count=dim, dtype=np.int64).reshape(-1, dim)