python - TypeError: &: 'float' 和 'numpy.float64' 不支持的操作数类型

标签 python numpy typeerror

<分区>

我正在尝试使用以下代码将连续变量转换为分类变量:

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)

但我收到以下错误:

---------------------------------------------------------------------------
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'

我本来认为 floatnumpy.float64 是兼容的,但事实似乎并非如此。

在这方面的任何帮助将不胜感激。

TIA。

最佳答案

在这里x>=0.25 & x<0.5 &执行 bitwise AND operation (例如, 1 & 52 为零,将被视为 False ),而您当然想检查 x>=0.25 是否and x<0.5是真的。

那么,这样做:

x>=0.25 and x<0.5

同样的错误在下一行。

关于python - TypeError: &: 'float' 和 'numpy.float64' 不支持的操作数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37818279/

相关文章:

python:将一个数字除以一个numpy数组

python - 如何在 numpy 的日期中模糊添加年份?

Python 3 : Functions dependent on other functions, 缺少参数?

javascript - typescript : cannot read property 'long_name' of null

javascript - 未捕获的类型错误 : rectangle. 绘制不是函数

python - 使用Python按 block 解析文件并从每个 block 中提取信息

python - 在 Gtk.TextView 中使用标记

python-3.x - JAX 与 NumPy 数组索引 - 越界行为

python - 需要更好的逻辑来将字符串的每个第 i 个字符与其反向字符串的每个第 i 个字符相加

python - pymodbus:请求创建和响应接收