pandas.DataFrame和numpy.array中的np.isreal行为不同

时间:2017-10-20 20:38:47

标签: python pandas numpy

我有array,如下所示

np.array(["hello","world",{"a":5,"b":6,"c":8},"usa","india",{"d":9,"e":10,"f":11}])

pandas DataFrame如下

df = pd.DataFrame({'A': ["hello","world",{"a":5,"b":6,"c":8},"usa","india",{"d":9,"e":10,"f":11}]})

当我将np.isreal应用于DataFrame

df.applymap(np.isreal)
Out[811]: 
       A
0  False
1  False
2   True
3  False
4  False
5   True

np.isreal数组为numpy时。

np.isreal( np.array(["hello","world",{"a":5,"b":6,"c":8},"usa","india",{"d":9,"e":10,"f":11}]))
Out[813]: array([ True,  True,  True,  True,  True,  True], dtype=bool)

我必须在错误的用例中使用np.isreal,但是你可以帮助我解决 结果不同的原因 吗?

3 个答案:

答案 0 :(得分:7)

部分答案是isreal仅用于类似数组的第一个参数。

您希望在每个元素上使用isrealobj来获取您在此处看到的行为:

In [11]: a = np.array(["hello","world",{"a":5,"b":6,"c":8},"usa","india",{"d":9,"e":10,"f":11}])

In [12]: a
Out[12]:
array(['hello', 'world', {'a': 5, 'b': 6, 'c': 8}, 'usa', 'india',
       {'d': 9, 'e': 10, 'f': 11}], dtype=object)

In [13]: [np.isrealobj(aa) for aa in a]
Out[13]: [True, True, True, True, True, True]

In [14]: np.isreal(a)
Out[14]: array([ True,  True,  True,  True,  True,  True], dtype=bool)

这确实留下了问题,np.isreal对不像数组的事情做了什么。

In [21]: np.isrealobj("")
Out[21]: True

In [22]: np.isreal("")
Out[22]: False

In [23]: np.isrealobj({})
Out[23]: True

In [24]: np.isreal({})
Out[24]: True

事实证明,这源于.imag,因为test that isreal does是:

return imag(x) == 0   # note imag == np.imag

就是这样。

In [31]: np.imag(a)
Out[31]: array([0, 0, 0, 0, 0, 0], dtype=object)

In [32]: np.imag("")
Out[32]:
array('',
      dtype='<U1')

In [33]: np.imag({})
Out[33]: array(0, dtype=object)

这会查找数组上的.imag属性。

In [34]: np.asanyarray("").imag
Out[34]:
array('',
      dtype='<U1')

In [35]: np.asanyarray({}).imag
Out[35]: array(0, dtype=object)

我不确定为什么在字符串的情况下还没有设置...

答案 1 :(得分:4)

我认为这是Numpy中的一个小错误。在这里,Pandas只是循环遍历列中的每个项目并在其上调用np.isreal()。 E.g:

>>> np.isreal("a")
False
>>> np.isreal({})
True

我认为这里的悖论与np.real()如何处理dtype=object的输入有关。我的猜测是它正在使用对象指针并将其视为一个int,所以当然np.isreal(<some object>)返回True。在np.array(["A", {}])之类的混合类型数组中,数组为dtype=object,因此np.isreal()dtype=object处理所有元素(包括字符串)。

为了清楚起见,我认为该错误是np.isreal()如何处理dtype=object数组中的任意对象,但我没有明确证实这一点。

答案 2 :(得分:1)

这里有几件事情要发生。首先通过前面的答案指出np.isreal在传递ojbects时行为奇怪。  但是,我认为你对applymap正在做的事情感到困惑。 Difference between map, applymap and apply methods in Pandas始终是一个很好的参考。

在这种情况下,您认为自己在做的事实上是:

df.apply(np.isreal, axis=1)

本质上调用np.isreal(df),而df.applymap(np.isreal)实际上是在df的每个单独元素上调用np.isreal。 e.g

np.isreal(df.A)

array([ True,  True,  True,  True,  True,  True], dtype=bool)

np.array([np.isreal(x) for x in df.A])

array([False, False,  True, False, False,  True], dtype=bool)