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

2023-12-12

我有一个array像下面这样

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

and a pandas DataFrame像下面这样

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

当我申请时np.isreal to DataFrame

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

当我做np.isreal为了numpy array.

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在错误的用例中,但是你能帮我吗为什么结果不同 ?


部分答案是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自从测试一下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数组上的属性。

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

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

我不确定为什么这还没有在字符串大小写中设置......

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

pandas.DataFrame 和 numpy.array 中的 np.isreal 行为不同 的相关文章

随机推荐