Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python matplotlib如何处理二进制数据?_Python_Matplotlib - Fatal编程技术网

Python matplotlib如何处理二进制数据?

Python matplotlib如何处理二进制数据?,python,matplotlib,Python,Matplotlib,我正在尝试使用matplotlib绘制从文件读取的二进制数据: import matplotlib.pyplot as plt try: f = open(file, 'rb') data = f.read(100) plt.plot(data) except Exception as e: print(e) finally: f.close() 但我得到了以下错误: 'ascii' codec can't decode byte 0xfd in po

我正在尝试使用matplotlib绘制从文件读取的二进制数据:

import matplotlib.pyplot as plt

try:
    f = open(file, 'rb')
    data = f.read(100)
    plt.plot(data)
except Exception as e:
    print(e)
finally:
    f.close()
但我得到了以下错误:

'ascii' codec can't decode byte 0xfd in position 0: ordinal not in range(128)

我正在读取的文件由二进制数据组成。那么matplotlib如何处理二进制数据呢?它是无符号的还是有符号的1字节数据

正如您在问题的评论中所指出的,传递给plot的字节是不明确的。在将这些字节传递给matplotlib之前,需要将其转换为numpy数组(或列表/元组)

一个简单的例子来说明这一点:

import numpy as np
import matplotlib.pyplot as plt


orig_array = np.arange(10, dtype=np.uint8)
with open('my_binary_data.dat', 'wb') as write_fh:
    write_fh.write(orig_array)

with open('my_binary_data.dat', 'rb') as fh:
    loaded_array = np.frombuffer(fh.read(), dtype=np.uint8)

print loaded_array
plt.plot(loaded_array)
plt.show()
在演示如何使用numpy.frombuffer和读入“data”变量的字节时,我已经绕了一圈,但实际上,您只需要使用numpy.fromfile,加载行如下所示:

loaded_array = np.fromfile(fh, dtype=np.uint8)

HTH

您希望
matplotlib
如何解释随机二进制数据?你在找什么样的绘图?@askewchan如果我打印
数据
,它打印为
b'\xfd\xd0\xfb\xcaM……
。所以我需要一个解析器将二进制数据解析为绘图函数的ASCII数据格式,对吗?@tonga二进制数据可以以一百万种不同的方式存储(实际上更多:)。例如,您可能在该二进制文件中有4字节长的整数值,或者您可能有64位浮点值,或者您可能有一个bzipped文本文件,等等。您需要首先了解数据在二进制数据文件中是如何组织的。将此信息作为此问题的一部分发布。答案在那个阶段可能是显而易见的。另外,如果你知道二进制文件中存储的数据的类型/格式,你可以用它将其读入数组。@tonga-正如crazeewulf已经指出的那样,
numpy.fromfile
对于你所描述的内容非常方便(如果数据不在文件中,还有
numpy.fromstring
frombuffer
)。如果需要未签名的字符,则执行
data=numpy.fromfile(yourfile,dtype=numpy.uint8)
,如果需要签名的字符,则执行
data=numpy.fromfile(yourfile,dtype=numpy.int8)
。如果不想使用numpy,请查看内置的
struct
array
模块。无论哪种方式,如果想要
uint
s,都需要将字符串转换为
uint
s序列。希望这有助于澄清问题。