.ix上的按位运算(Pandas)

时间:2013-03-18 15:55:49

标签: python-2.7 pandas dataframe

为什么开发人员不允许在.ix上进行按位操作?好奇这是技术约束还是我忽视的逻辑问题。

df.ix[df["ptdelta"]<=0 & df["ptdelta"]>5]

追溯是:

TypeError: ufunc 'bitwise_and' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule 'safe'

'''

注意:截至Pandas v0.20,.ix indexer is deprecated赞成.iloc / .loc

1 个答案:

答案 0 :(得分:7)

我认为你误解了方括号里面发生的事情 - .ix与它无关。如果你适当地加上括号,这可行:

>>> df = pd.DataFrame({"a": [-1,2,-3,4,6,-8.2]})
>>> df.ix[(df['a'] <= 0) | (df['a'] > 5)]
     a
0 -1.0
2 -3.0
4  6.0
5 -8.2

否则你试图在(假设)浮点数上执行按位运算。例如,如果它是一个int,则它“工作”:

>>> df['a'] <= 0 & df['a']
Traceback (most recent call last):
  File "<ipython-input-40-9173361ec31b>", line 1, in <module>
    df['a'] <= 0 & df['a']
TypeError: ufunc 'bitwise_and' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule 'safe'

>>> df['a'] <= 0 & df['a'].astype(int)
0     True
1    False
2     True
3    False
4    False
5     True
Name: a, Dtype: bool