簡體   English   中英

代碼中的“無效類型比較”

[英]'Invalid type comparison' in the code

我有一個pandas dataframe ,其中有很多列。 這些列可能具有3個值-True,False和NaN。 我正在用missing的字符串替換NaN 我的其中一列的樣本值如下:

ConceptTemp.ix[:,1].values

導致:

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

請注意,此特定列沒有NaN ,因此沒有missing字符串。

現在,我執行以下代碼:

ConceptTemp.ix[:,1][ConceptTemp.ix[:,1] != 'missing'].values

要獲得以下異常:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-47-0a0b76cf3ab5> in <module>()
----> 1 ConceptTemp.ix[:,1][ConceptTemp.ix[:,1] != 'missing'].values

E:\Anaconda2\lib\site-packages\pandas\core\ops.pyc in wrapper(self, other, axis)
    724                 other = np.asarray(other)
    725 
--> 726             res = na_op(values, other)
    727             if isscalar(res):
    728                 raise TypeError('Could not compare %s type with Series'

E:\Anaconda2\lib\site-packages\pandas\core\ops.pyc in na_op(x, y)
    680                 result = getattr(x, name)(y)
    681                 if result is NotImplemented:
--> 682                     raise TypeError("invalid type comparison")
    683             except AttributeError:
    684                 result = op(x, y)

TypeError: invalid type comparison

有人知道如何解決嗎?

任何指針將不勝感激。

正如人們評論的那樣,在數組中組合類型(即帶有布爾值的字符串)有點奇怪。 您將獲得布爾數組可能與您想像的結果不符的結果。 但是,如果您絕對必須這樣做,則可以通過以下兩種方法進行。 第一個是與isin

In [40]: ConceptTemp.ix[:,0][~ConceptTemp.ix[:,0].isin(['missing'])].values
Out[40]:
         array([ True, False, False, False,  True,  True,  True,  True, False,  True], dtype=bool)

第二個是與applylambda

In [41]: ConceptTemp.ix[:,0][ConceptTemp.ix[:,0].apply(lambda x: x != 'missing')].values
Out[41]:
         array([ True, False, False, False,  True,  True,  True,  True, False,  True], dtype=bool)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM