【问题标题】:Numpy isclose for Arrays - TypeError: Not implemented for this typeNumpy isclose for Arrays - TypeError:未为此类型实现
【发布时间】:2019-10-21 02:19:52
【问题描述】:

我有 2 个 .csv (.tsv) 表,我将它们加载到数组中。现在我想通过 numpy isclose 函数比较这两个数组的每个单元格。

它适用于普通数字,但不适用于我的数组。

with open(filename) as csv_file:
    reader = csv.reader(csv_file, delimiter='\t')
    for row in reader:
        point.append(row[0])

with open(filename2) as csv_file:
    reader = csv.reader(csv_file, delimiter='\t')
    for row in reader:
        point2.append(row[0])

print(numpy.isclose(point,point2, atol=0.01))

错误:

print(numpy.isclose(point,point2, atol=0.01))
  File "C:\Python27\lib\site-packages\numpy\core\numeric.py", line 2306, in isclose
    xfin = isfinite(x)
TypeError: Not implemented for this type

即使我尝试从数组中直接输入(例如 point[3]、point2[3]),我还是会出错。

【问题讨论】:

  • 您的 csv 文件的内容是什么?据我所知,您只能使用 numpy.isclose 比较数字。如果您的 csv 文件只包含数字,您需要先将阅读器提供的字符串转换为数字。即 print(numpy.isclose(point.astype(np.float),point2.astype(np.float), atol=0.01))
  • pointpoint2 是列表。 isclose 必须将它们转换为数组 (np.array(point)) 来比较它们。它需要数字数组,没有字符串。当它尝试检查其中一个数组的 np.inf 值时,会发生错误,这是一个浮点操作。首先构造正确的numpy 数组,检查dtype,并根据需要进行修改。如果不完全了解加载的内容,就无法开始比较它们。

标签: python arrays csv numpy


【解决方案1】:

csv.reader 读取字符串——最终得到两个字符串列表。

当您阅读这些行时,您可能希望将值转换为 float(或者如果您需要更精确的其他值)。

with open(filename) as csv_file:
    reader = csv.reader(csv_file, delimiter='\t')
    point1 = [float(row[0]) for row in reader]

with open(filename2) as csv_file:
    reader = csv.reader(csv_file, delimiter='\t')
    point2 = [float(row[0]) for row in reader]

print(numpy.isclose(point1, point2, atol=0.01))

【讨论】:

    猜你喜欢
    • 2016-03-06
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    • 1970-01-01
    • 2020-05-26
    • 1970-01-01
    • 1970-01-01
    • 2020-06-24
    相关资源
    最近更新 更多