Python 类型错误:& 不支持的操作数类型:'float' 和 'numpy.float64'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37818279/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: unsupported operand type(s) for &: 'float' and 'numpy.float64'
提问by Patthebug
I'm trying to convert a continuous variable to a categorical variable using the following code:
我正在尝试使用以下代码将连续变量转换为分类变量:
def score_to_categorical(x):
if x<0.25:
return 'very bad'
if x>=0.25 & x<0.5:
return 'bad'
if x>=0.5 & x<0.75:
return 'good'
else:
return 'very good'
ConceptTemp['Score'] = ConceptTemp['Score'].apply(score_to_categorical)
ConceptTemp1['Score'] = ConceptTemp1['Score'].apply(score_to_categorical)
but I get the following error:
但我收到以下错误:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-72-7ec42b055d4f> in <module>()
----> 1 ConceptTemp['Score'] = ConceptTemp['Score'].apply(score_to_categorical)
2 ConceptTemp1['Score'] = ConceptTemp1['Score'].apply(score_to_categorical)
E:\Anaconda2\lib\site-packages\pandas\core\series.pyc in apply(self, func, convert_dtype, args, **kwds)
2167 values = lib.map_infer(values, lib.Timestamp)
2168
-> 2169 mapped = lib.map_infer(values, f, convert=convert_dtype)
2170 if len(mapped) and isinstance(mapped[0], Series):
2171 from pandas.core.frame import DataFrame
pandas\src\inference.pyx in pandas.lib.map_infer (pandas\lib.c:62578)()
<ipython-input-11-1c4f9c7bfafe> in score_to_categorical(x)
10 if x<0.25:
11 return 'very bad'
---> 12 if x>=0.25 & x<0.5:
13 return 'bad'
14 if x>=0.5 & x<0.75:
TypeError: unsupported operand type(s) for &: 'float' and 'numpy.float64'
I would've though that floatand numpy.float64would be compatible but that doesn't seem to be the case.
我会考虑到这一点float并且numpy.float64会兼容,但情况似乎并非如此。
Any help in this regard would be much appreciated.
在这方面的任何帮助将不胜感激。
TIA.
TIA。
回答by ForceBru
Here x>=0.25 & x<0.5&performs a bitwise AND operation(for example, 1 & 52is zero, which will be treated as False), while you certainly meant to check whether both x>=0.25andx<0.5are true.
这里x>=0.25 & x<0.5&执行按位 AND 运算(例如,1 & 52为零,将被视为False),而您当然想检查x>=0.25和是否都x<0.5为真。
So, do this:
所以,这样做:
x>=0.25 and x<0.5
The same mistake is on the next line.
同样的错误出现在下一行。

