我有一个pandas dataframe
,它有很多列。这些列可能有3个值 - True,False和NaN。我使用字符串NaN
重新填充missing
。我的一个列的示例值如下:
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
有人知道如何修复它吗?
任何指针都会受到高度赞赏。
答案 0 :(得分:3)
正如人们评论的那样,在数组中组合类型(即字符串与布尔值)有点奇怪。您将获得结果,其中布尔数组可能不是您认为的那样。但是如果你绝对必须这样做,你可以通过几种方式来做这件事。第一个是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)
第二个是apply
和lambda
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)