[英]Reading text file into structured 2D numpy array
I have a structured 2D numpy array of shape: [2,2]我有一个结构化的 2D numpy 形状数组:[2,2]
filled example [2,2] array:填充示例 [2,2] 数组:
Main_Clt_data_array: Main_Clt_data_array:
[ [ ((10, 10), 20, 300.) ((20, 20), 20, 300.) ]
[((30, 30), 30, 300.) ((40, 40), 40, 300.)] ]
It is of the following datatype它具有以下数据类型
Cord_dtype = np.dtype([('X', np.float64), ('Y', np.float64)])
Clt_data_dtype=np.dtype([('Coord', Cord_dtype),('Angle', np.float64), ('Length', np.float64)])
Using np.savetxt
i was able to save the array into a txt file maintaing same shape and order.使用
np.savetxt
我能够将数组保存到一个保持相同形状和顺序的 txt 文件中。
'Trial.txt': enter image description here 'Trial.txt':在此处输入图像描述
but when i try to read into python using genfromtxt,It does not work.: example:但是当我尝试使用 genfromtxt 读取 python 时,它不起作用。:示例:
read_array = np.genfromtxt('Trial.txt',dtype=Clt_data_dtype)
OUTPUT : OUTPUT :
('READ_ARRAY_shape :', (2L,))
('READ_ARRAY :', array([((nan, nan), nan, nan), ((nan, nan), nan, nan)], 'V32'))
Hope some one could guide me and Thanks in advance for any input希望有人可以指导我并提前感谢您的任何意见
also note i cannot use pandas as i am running it only numpy compatable program还要注意我不能使用 pandas 因为我只运行它 numpy 兼容程序
In [17]: Cord_dtype = np.dtype([('X', np.float64), ('Y', np.float64)])
...: Clt_data_dtype=np.dtype([('Coord', Cord_dtype),('Angle', np.float64), ('Length', np.float64)])
Creating your array:创建你的数组:
In [18]: arr = np.array([ [ ((10, 10), 20, 300.), ((20, 20), 20, 300.) ],
...: [((30, 30), 30, 300.), ((40, 40), 40, 300.)] ], dtype=Clt_data_dtype)
...:
...:
In [19]: arr
Out[19]:
array([[((10., 10.), 20., 300.), ((20., 20.), 20., 300.)],
[((30., 30.), 30., 300.), ((40., 40.), 40., 300.)]],
dtype=[('Coord', [('X', '<f8'), ('Y', '<f8')]), ('Angle', '<f8'), ('Length', '<f8')])
In [20]: arr.shape
Out[20]: (2, 2)
genfromtxt
can recreate it from a csv
style file like: genfromtxt
可以从csv
样式文件重新创建它,例如:
In [21]: txt = """10 10 20 300.
...: 20 20 20 300.
...: 30 30 30 300.
...: 40 40 40 300.
...: """
In [22]: np.genfromtxt(txt.splitlines(), dtype=Clt_data_dtype)
Out[22]:
array([((10., 10.), 20., 300.), ((20., 20.), 20., 300.),
((30., 30.), 30., 300.), ((40., 40.), 40., 300.)],
dtype=[('Coord', [('X', '<f8'), ('Y', '<f8')]), ('Angle', '<f8'), ('Length', '<f8')])
In true csv
fashion this just contains rows and columns of numbers.在真正的
csv
中,它只包含数字的行和列。 It does not have the delimiters and ()
that your img
shows.它没有您的
img
显示的分隔符和()
。 It may be possible to parse your image and create the file, but a csv
reader can't handle.可以解析您的图像并创建文件,但
csv
阅读器无法处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.