arrays - 将 Numpy/Pandas 数组与混合元素(字符串和 float )进行比较

标签 arrays pandas numpy comparison

我有一些我希望比较的 Numpy 数组(或等效的 Pandas 数据帧,因为它可以很容易地转换成)。这些数组/数据帧包含数字和字符串。

对于纯数字,我可以执行以下操作。

import numpy as np
a = np.array([[1.0, 2.0], [1.00001, 2.00001]])
b = np.array([[1.000001, 2.00001], [1.00001, 2.00001]])
print(np.allclose(a, b, 1e-9))
# output: False
print(np.allclose(a, b, 1e-4))
# output: True

使用以下混合数组时,我收到错误。

c = np.array([[1.0, "Cat"], [1.00001, 2.00001]])
d = np.array([[1.000001, "Dog"], [1.00001, 2.00001]])
e = np.array([[1.000001, "Cat"], [1.00001, 2.00001]])
print(np.allclose(c, d, 1e-4))
# expected output: False on account of the string difference
print(np.allclose(c, e, 1e-4))
# expected output: True

我尝试将其转换为 Pandas 数据框,希望内置测试模块可以解决问题。

import pandas as pd
from pandas.util import testing as pdtest
df_c = pd.DataFrame(c)
df_d = pd.DataFrame(d)
df_e = pd.DataFrame(e)
print(pdtest.assert_almost_equal(df_c, df_e, check_exact=False, check_less_precise=4))
# expected output: True as the strings match and numbers agree within tolerance.

但这行不通。有没有一种方法可以比较数组,其中数字元素与指定的容差进行比较,而字符串元素则进行精确比较?

编辑:公差纯粹是针对 float 元素的。对于字符串,需要精确匹配。

最佳答案

def myequal(i,j):
    # scalar comparison function of your own design
    if isinstance(i,str):
        return i==j
    else:
        return 1e04>abs(i-j)

示例数组,作为对象数据类型:

In [74]: c = np.array([[1.0, "Cat"], [1.00001, 2.00001]],object)
    ...: d = np.array([[1.000001, "Dog"], [1.00001, 2.00001]],object)
    ...: e = np.array([[1.000001, "Cat"], [1.00001, 2.00001]],object)

In [75]: c
Out[75]: 
array([[1.0, 'Cat'],
       [1.00001, 2.00001]], dtype=object)
In [76]: d
Out[76]: 
array([[1.000001, 'Dog'],
       [1.00001, 2.00001]], dtype=object)
In [77]: e
Out[77]: 
array([[1.000001, 'Cat'],
       [1.00001, 2.00001]], dtype=object)

使用 frompyfuncmyequal 应用于 to 数组的元素。基本上它负责广播迭代

In [78]: f = np.frompyfunc(myequal,2,1)
In [79]: f(c,d)
Out[79]: 
array([[True, False],
       [True, True]], dtype=object)
In [80]: f(c,e)
Out[80]: 
array([[True, True],
       [True, True]], dtype=object)

没有 object dtype,你的数组是字符串 dtype,唯一常见的 dtype:

In [81]: np.array([[1.0, "Cat"], [1.00001, 2.00001]])
Out[81]: 
array([['1.0', 'Cat'],
       ['1.00001', '2.00001']], dtype='<U32')

这会在 allclose/isclose 中引发错误,因为无法针对 np.inf 测试字符串:

In [82]: np.isclose(_,_)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-82-c2e4de5fe672> in <module>()
----> 1 np.isclose(_,_)

/usr/local/lib/python3.6/dist-packages/numpy/core/numeric.py in isclose(a, b, rtol, atol, equal_nan)
   2330     y = array(y, dtype=dt, copy=False, subok=True)
   2331 
-> 2332     xfin = isfinite(x)
   2333     yfin = isfinite(y)
   2334     if all(xfin) and all(yfin):

TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

np.isfinite 适用于数值数组,不适用于字符串数组。

关于arrays - 将 Numpy/Pandas 数组与混合元素(字符串和 float )进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50554750/

相关文章:

python - 如何一次创建多个数组

java - 从用户输入中读取名称并将其存储在数组中

java - 使用Java将HSQLDB表中的数据转换为二维数组

python - 根据列值创建组

python - 用 Pandas 计算滚动平均数

python - 从 Numpy 结果分配 Koalas 列

arrays - Swift 错误 - 无法将类型 'MKOverlay' 的值转换为预期的参数类型 '@noescape (MKOverlay) throws -> Bool' - 执行 indexOf 时

c - 使用 memset 初始化三值结构数组

python - 为什么bokeh应用回调会转换变量类型? (ColumnDataSource 到 pandas df)

python - numpy.concatenation 的问题