[英]np.isreal behavior different in pandas.DataFrame and 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
,但是你可以幫我解釋為什么結果不同嗎?
部分答案是, 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
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)
我不知道為什么在字符串的情況下還沒有設置...
我認為這是Numpy的一個小錯誤,說實話。 在這里,Pandas只是循環遍歷列中的每個項目並在其上調用np.isreal()
。 例如:
>>> np.isreal("a")
False
>>> np.isreal({})
True
我認為這里的悖論與np.real()
如何處理np.real()
dtype=object
輸入有關。 我的猜測是它采用了對象指針並將其np.isreal(<some object>)
一個int,所以當然np.isreal(<some object>)
返回True。 在像np.array(["A", {}])
這樣的混合類型數組中,數組是np.isreal()
dtype=object
所以np.isreal()
正在處理所有元素(包括字符串)的方式dtype=object
。
為了清楚np.isreal()
,我認為錯誤在於np.isreal()
如何處理np.isreal()
dtype=object
數組中的任意對象,但我沒有明確地證實這一點。
這里有幾件事情要發生。 首先通過前面的答案指出, np.isreal
在傳遞ojbects時表現np.isreal
奇怪。 但是,我認為你也對applymap
感到困惑。 Pandas中map,applymap和apply方法之間的區別總是很好的參考。
在這種情況下,您認為自己在做的事實上是:
df.apply(np.isreal, axis=1)
其實質上是調用np.isreal(df),而df.applymap(np.isreal)實際上是在df的每個元素上調用np.isreal。 例如
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.