使用Numpy的readtxt读取十六进制数字 [英] Using Numpy's readtxt to read Hex numbers

查看:866
本文介绍了使用Numpy的readtxt读取十六进制数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只能从文本文件中读取整数值,但是当我尝试以十六进制格式读取整数时,会发生错误.我正在使用的代码行是

I am only able to read integer values from a text file, but when I try to read integers in Hex format, an error occurs. The code line I'm using is

output = np.loadtxt(fidOut, dtype="int32", delimiter="\n");

你能帮我吗?

推荐答案

您需要添加一个转换器,以便numpy理解如何解释十六进制数据.

You need to add a converters so that numpy understands how to interpret the hex-data.

对于具有如下数据的简单文件test.csv:

For a simple file test.csv with data as follows:

af,2b,10    
3aaa,4a,fa

您需要为所有三列指定转换器:

You would need to specify converters for all three columns:

In [2]: np.loadtxt("test.csv", dtype='int32', delimiter=',', converters={_:lambda s: int(s, 16) for _ in range(3)})
Out[2]: 
array([[  175,    43,    16],
       [15018,    74,   250]], dtype=int32)

提供的字典以列索引作为键,以转换器作为值. 根据十六进制数据在文件中的表示方式,您可能需要修改上面的lambda-表达式.

The dictionary supplied has column-index as keys and converters as values. Depending on how your hex-data is represented in the file you may need to modify the lambda-expression above.

这篇关于使用Numpy的readtxt读取十六进制数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆