在python 3中使用genfromtxt函数时,numpy引发错误 [英] Numpy throws error while using genfromtxt function in python 3
本文介绍了在python 3中使用genfromtxt函数时,numpy引发错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的示例代码将是这样
import numpy as np
from io import BytesIO
data = "1, 2, 3\n4, 5, 6"
np.genfromtxt(data, delimiter=",")
在运行此代码时抛出错误
while run this code throws error
回溯(最近通话最近): 文件",第1行,在 TypeError:需要一个类似字节的对象,而不是'str'
Traceback (most recent call last): File "", line 1, in TypeError: a bytes-like object is required, not 'str'
推荐答案
在读取字符串之前先对其进行编码:
Encode the string before reading it:
data = "1, 2, 3\n4, 5, 6"
np.genfromtxt(BytesIO(data.encode()), delimiter=",")
array([[ 1., 2., 3.],
[ 4., 5., 6.]])
这篇关于在python 3中使用genfromtxt函数时,numpy引发错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文