【问题标题】:Numpy throws error while using genfromtxt function in python 3在 python 3 中使用 genfromtxt 函数时 Numpy 抛出错误
【发布时间】:2017-12-31 03:16:48
【问题描述】:

我的示例代码会是这样的

import numpy as np
from io import BytesIO

data = "1, 2, 3\n4, 5, 6"
np.genfromtxt(data, delimiter=",")

运行此代码时抛出错误

Traceback(最近一次调用最后一次): 文件“”,第 1 行,在 TypeError:需要一个类似字节的对象,而不是'str'

【问题讨论】:

  • 我认为你想要 np.genfromtxt(BytesIO(data), delimiter=",") 错误表明它不喜欢字符串
  • 不应该读成BytesIO(data.encode())吗?
  • this会有帮助

标签: python numpy


【解决方案1】:

在读取之前对字符串进行编码:

data = "1, 2, 3\n4, 5, 6"
np.genfromtxt(BytesIO(data.encode()), delimiter=",")

array([[ 1.,  2.,  3.],
       [ 4.,  5.,  6.]])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多