Np.isreal behavior is different from pandas.DataFrame and numpy.array

I have arrayas below

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

and a pandas DataFrameas shown below

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

When i apply np.isrealtoDataFrame

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

When I do np.isrealfor an array 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)

I have to use np.isrealin the wrong use case. But can you help me about why the result is different from ?

+6
source share
3 answers

The partial answer is that it isrealis only for use in the array as the first argument.

You want to use isrealobjfor each element to get baavior 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 , , .

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 :

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)

, ...

+6

, Numpy, . Pandas np.isreal(). :.

>>> 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, .

+4

A couple of things happen here. The first ones are mentioned in previous answers by the fact that it np.isrealacts strange when passing ojbect. However, I think you are also embarrassed by what you are doing applymap. The difference between the map, applymap, and apply methods in Pandas is always a great reference.

In this case, what you think you are doing is actually:

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

Which essentially calls np.isreal (df), while df.applymap (np.isreal) essentially calls np.isreal for each individual df element. eg

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)
+1
source

All Articles