简体   繁体   English

为什么 numpy 在这里返回一维数组?

[英]why is numpy returning a 1-d array here?

I'm trying to read a numpy array from a big file of binary data.我正在尝试从二进制数据的大文件中读取一个 numpy 数组。 Each binary record contains 7330 floats, followed by a long I want to ignore, and then an int.每个二进制记录包含 7330 个浮点数,后跟一个我想忽略的 long,然后是一个 int。 I create a dtype as follows:我创建一个 dtype 如下:

dt = [(str(n),'f4') for n in range(7330)]
dt += [('junk','i8'), ('label','i4')]

and then read the file via然后通过读取文件

d = np.fromfile(file_name,dtype=np.dtype(dt))

It works, but I get back a one-dimensional array or records instead of the 2-D array I want.它有效,但我得到一个一维数组或记录,而不是我想要的二维数组。 Somewhat more specifically, I get back an array with d.shape=(58134,) d[0] of type numpy.void and len(d[0])=7332 (7330 floats, the long I will ignore, and the int).更具体地说,我得到了一个数组,其中d.shape=(58134,) d[0]类型为numpy.voidlen(d[0])=7332 (7330 个浮点数,我将忽略的 long 和 int )。 I want an array of shape (58134,7332) .我想要一个形状数组(58134,7332)

I can't d.reshape(-1,7332) because d is one dimensional, and I wind up converting it via the ugly and somewhat absurd我不能 d.reshape(-1,7332) 因为 d 是一维的,我最终通过丑陋和有点荒谬的方式转换它

nparray = pd.DataFrame.from_records(d).to_numpy()

which seems just ridiculous.这似乎很荒谬。 What am I doing wrong?我究竟做错了什么? Thanks!谢谢!

Turns out that numpy.lib.recfunctions.structured_to_unstructured does exactly this.事实证明 numpy.lib.recfunctions.structured_to_unstructured 正是这样做的。 Thanks to darcamo for pointing me in that direction.感谢 darcamo 为我指明了那个方向。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM