【问题标题】:TypeError: ufunc 'bitwise_and' not supported for the input typesTypeError:输入类型不支持 ufunc 'bitwise_and'
【发布时间】:2023-03-30 14:15:01
【问题描述】:

我正在尝试编写一些代码,让我可以快速确定一个变量是否高于、低于或等于数据框中每个索引点的另一个变量。

如下图:

import numpy as np
import datetime
import pandas as pd
import operator

previous_cross = 'both'

ops = {
    '+' : operator.add,
    '-' : operator.sub,
    '*' : operator.mul,
    '/' : operator.truediv,  # use operator.div for Python 2
    '%' : operator.mod,
    '^' : operator.xor,
    '<' : operator.lt,
    '<=' : operator.le,
    '==' : operator.eq,
    '!=' : operator.ne,
    '>=' : operator.ge,
    '>' : operator.gt
} 

#//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

df = pd.read_csv(r'C:\EURUSD_mt5_ticks.csv', parse_dates=['Date'])
df.columns = ['Date', 'Ask_Price', 'Ask_Volume', 'Bid_Price', 'Bid_Volume', 'Spread']
df['Date'] = pd.to_datetime(df['Date'].astype('datetime64[ns]'), exact=True, cache=True, format='%Y-%m-%d  %H:%M:%S.%f')  
MA1 = df['Ask_Price'].rolling(4).mean()
MA2 = df['Ask_Price'].rolling(21).mean()
df['MA1'] = MA1
df['MA2'] = MA2

#//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

def tbar_number(n):
        return tbar_count - n

    
def vcross(variable1_column, direction, variable2_column, vdataframe, width):

    global previous_cross


    
    #number of bars previous from the current bar, 
    width_value = tbar_number(width)
    
    for i in range(width_value+1):

        width_value_count = i
  
        #data from the index of each bar within the 'width' bar range
        v1_width_data = df.loc[width_value_count, variable1_column] 
        v2_width_data = df.loc[width_value_count, variable2_column]
                                    
            #if variable 1 crosses above or is equal to(depending on chosen symbol) variable 2, return true
        if (direction == '>' or '>=') & (ops[direction](v1_width_data, v2_width_data)) & (previous_cross == 'short' or 'both'):
            if (direction == '>=') and (v1_width_data == v2_width_data):
                return True
            if direction == '>':
                previous_cross = 'long'  
                return True
        
             #if variable 1 crosses below or is equal to(depending on chosen symbol) variable 2, return true
        elif (direction == '<' or '<=') & (ops[direction](variable1, variable2)) & (previous_cross == 'long' or 'both'):
            if (direction == "<=") and (v1_width_data == v2_width_data): 
                return True
            if direction == '<':
                previous_cross = 'short'
                return True

             #if variable 1 is equal to(depending on chosen symbol) variable 2, return true
        elif (direction == '==') & (ops[direction](variable1, variable2)):
            return True
        
        else:
            return False
        
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
for tbar_count in range(len(df)): 
    
  if vcross('MA1', '>', 'MA2', df, 1):
  print("hi")

数据框数据


Date    Ask_Price   Ask_Volume  Bid_Price   Bid_Volume  Spread  MA1 MA2
0   2021-08-11 00:00:00.686 1.17199 0.75    1.17195 0.75    0.00004 NaN NaN
1   2021-08-11 00:00:00.989 1.17201 2.43    1.17195 3.37    0.00006 NaN NaN
2   2021-08-11 00:00:05.004 1.17198 0.75    1.17196 4.87    0.00002 NaN NaN
3   2021-08-11 00:00:05.203 1.17200 0.75    1.17197 0.10    0.00003 1.171995    NaN
4   2021-08-11 00:00:10.654 1.17201 0.75    1.17198 0.10    0.00003 1.172000    NaN

但我得到了这个错误

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-f2dbb6db13b8> in <module>
     80 for tbar_count in range(len(df)):
     81 
---> 82     if vcross('MA1', '>', 'MA2', df, 1):
     83         print("hi")
     84 

<ipython-input-7-f2dbb6db13b8> in vcross(variable1_column, direction, variable2_column, vdataframe, width)
     55 
     56             #if variable 1 crosses above or is equal to(depending on chosen symbol) variable 2, return true
---> 57         if (direction == '>' or '>=') & (ops[direction](v1_width_data, v2_width_data)) & (previous_cross == 'short' or 'both'):
     58             if (direction == '>=') and (v1_width_data == v2_width_data):
     59                 return True

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

我无法通过谷歌找到解决方案。 大多数情况下,问题似乎与使用 & 时未封装条件有关,但我已经封装了所有内容。

谁能帮帮我?

【问题讨论】:

  • 测试第 57 行中的每个操作以确定哪个引发了错误。 &amp; 只能比较布尔值。
  • 似乎最后一个条件是问题所在。它说它是一个字符串。但是所有这三个条件都是布尔值。它们在单独运行时显示 True 或 False。为什么最后一个条件被归类为字符串?
  • previous_cross == 'short' or 'both' 如果previous_cross 不等于“短”,则返回一个字符串。应该是... or previous_cross == 'both'

标签: python-3.x pandas dataframe numpy


【解决方案1】:

在测试中小心使用or。例如:

In [351]: direction='++'; direction=='>' or '>='
Out[351]: '>='
In [352]: direction='>'; direction=='>' or '>='
Out[352]: True

这是一个direction=='&gt;';如果为真,则返回真;如果为 False,则返回 or 之后的值。不一样

In [354]: direction='++';(direction=='>') or (direction=='>=')
Out[354]: False
In [355]: direction='>';(direction=='>') or (direction=='>=')
Out[355]: True
In [356]: direction='>=';(direction=='>') or (direction=='>=')
Out[356]: True

等价的测试是

direction in ['>','>=']

【讨论】:

    猜你喜欢
    • 2020-07-21
    • 2020-09-29
    • 1970-01-01
    • 1970-01-01
    • 2017-09-17
    • 2018-03-09
    • 1970-01-01
    • 2020-02-16
    • 2021-12-01
    相关资源
    最近更新 更多