使用 pandas 数据框和组合条件会产生歧义错误

Working with pandas dataframe and Combining conditions gives ambiguity error

我正在尝试计算称为十字星的烛条形态。需要两个条件的两次计算 values 是一个 pandas 数据框,其中包含包含日期、最高价、最低价、开盘价和收盘价列的历史股票数据。

在 if 条件下,我尝试显式地使 condition1 和 condition2 为布尔值,并且还尝试通过使用 any() 对其进行类型转换来进行尝试。他们两个都没有给出所需的 result.Printing 条件 1 和条件 2 分别给出适当的布尔值,但将它与 '&' 结合起来就大错特错了。

51315    True
51316    True
51317    True
51318    True
51319    True
         ... 
53790    True
53791    True
53792    True
53793    True
53794    True
Length: 2480, dtype: bool

ValueError                                Traceback (most recent call last)
<ipython-input-58-3f42eed169f4> in <module>
      4 values = pd.DataFrame(stocks_data.loc[stocks_data['Company']=='TCS'])
      5 values.reset_index()
----> 6 study_candlesticks(values)

<ipython-input-57-fd67b4117699> in study_candlesticks(values)
     21 #     for row in values
     22 
---> 23     if calc_doji(values):
     24         values['Pattern']='Doji'
     25 

<ipython-input-57-fd67b4117699> in calc_doji(values)
     81     condition2=((values['High'] - values['Low'])>values['Close']*min_candle_size)
     82     print(condition2)
---> 83     if ((condition1).bool()&(condition2).any()):
     84         return True
     85     else:

~\Anaconda3\lib\site-packages\pandas\core\generic.py in bool(self)
   1581             )
   1582 
-> 1583         self.__nonzero__()
   1584 
   1585     def __abs__(self):

~\Anaconda3\lib\site-packages\pandas\core\generic.py in __nonzero__(self)
   1553             "The truth value of a {0} is ambiguous. "
   1554             "Use a.empty, a.bool(), a.item(), a.any() or a.all().".format(
-> 1555                 self.__class__.__name__
   1556             )
   1557         )

ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

我不确定我哪里出错了。有什么建议吗?

下面是代码

calc_doji(values)

def calc_doji(values):
    max_candle_size=0.1/100
    min_candle_size=1/100
    condition1 =(abs(values['Open'] - values['Close'])<values['Close']*max_candle_size)
    print(condition1)
    condition2=((values['High'] - values['Low'])>values['Close']*min_candle_size)
    print(condition2)
    if ((condition1).bool()&(condition2).any()): 
        return True
    else:
        return False

如果你有两个 pd.Series,其中 dtype('bool')。您可以通过以下方式比较它们。 在不知道你的数据是什么样子的情况下,我用 TrueFalse 创建了两个 pd.Series

import pandas as pd
import numpy as np

condition1= pd.Series(np.random.choice([True, False], 100)) 
condition2= pd.Series(np.random.choice([True, False], 100)) 

那么您可以通过以下方式进行比较。

(condition1) & (condition2) # which returns a `pd.Series` where each row is either `True` or `False`.

从每个 pd.Series 中找到任何索引位置,其中两个值都是 True.

((condition1) & (condition2)).any() # Which returns either `True` or `False`

根据你的代码,我猜这行就是问题所在。

if ((condition1).bool()&(condition2).any()):

应该是

if ((condition1) & (condition2)).any():