np.isreal行为在pandas.DataFrame和numpy.array中有所不同 [英] np.isreal behavior different in pandas.DataFrame and numpy.array

查看:257
本文介绍了np.isreal行为在pandas.DataFrame和numpy.array中有所不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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

当我对numpy数组执行np.isreal时.

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,但是您可以帮助我 为什么结果不同 吗?

I must using the np.isreal in the wrong use case, But can you help me about why the result is different ?

推荐答案

部分答案是

A partial answer is that isreal is only intended to be used on array-like as the first argument.

您要使用 isrealobj 在每个元素上获得您在此处看到的行为:

You want to use isrealobj on each element to get the bahavior you see here:

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对不像数组的东西做什么?

That does leave the question, what does np.isreal do on something that isn't array-like e.g.

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,因为测试isreal的行为是:


It turns out this stems from .imag since the test that isreal does is:

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属性.

This looks up the .imag attribute on the array.

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

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

我不确定为什么尚未在字符串大小写中设置此值...

I'm not sure why this isn't set in the string case yet...

这篇关于np.isreal行为在pandas.DataFrame和numpy.array中有所不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆