【问题标题】:pandas error: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()pandas 错误:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()
【发布时间】:2020-10-15 20:01:18
【问题描述】:

我有一个数据框。

distdf=pd.DataFrame(dist)
for i in range(len(distdf)):
    if distdf.loc[i]==distdf.loc[i+1]:
        print("true")
    else:
        print('no')

但我有一个错误。

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

我该如何解决?

【问题讨论】:

    标签: python pandas dataframe pandas-loc


    【解决方案1】:

    您的代码失败,因为 distdf.loc[i] == distdf.loc[i+1] 尝试 比较整行,即两个Series对象。

    如果你写了一些改进,那就是: if distdf.loc[i, 'DISTINGUISH']==distdf.loc[i+1, 'DISTINGUISH']:, 即比较每一行中的 DISTINGUISH 元素(当前和下一个)。

    但是这段代码在循环的最后一圈也会失败,因为 当你“停留”在最后一行时,没有下一行,那么 KeyError 引发异常。

    有一种更简单、更 pandasonic 的方法来获取您的值列表, 没有任何循环。

    假设您的 DataFrame (distdf) 包含:

        DISTINGUISH
    0             1
    1             1
    2             2
    3             2
    4             3
    5             3
    6            32
    7            32
    8            33
    9            33
    10           34
    11           34
    

    由于您想对其唯一的列进行操作,以保持代码简短, 让我们把它保存在 col0 下:

    col0 = distdf.iloc[:, 0]
    

    然后,要获取您的值列表,无需任何循环,运行:

    np.where(col0 == col0.shift(-1), 'true', 'no')
    

    上述数据的结果是:

    array(['true', 'no', 'true', 'no', 'true', 'no', 'true', 'no', 'true',
           'no', 'true', 'no'], dtype='<U4')
    

    【讨论】:

      【解决方案2】:

      尽管您只有一列,distdf.loc[i] 仍然是 Pandas Series 对象,而不仅仅是包含在唯一列中的整数,因此会出现错误。

      您可以做的是使用.values 比较单个列的每个单元格的值以避免出现此错误:

      # you also need to use len(distdf)-1 and not len(distdf)
      for i in range(len(distdf)-1):
          if distdf.loc[i].values == distdf.loc[i+1].values:
              print("true")
          else:
              print('no')
      

      【讨论】:

        【解决方案3】:
        dist =[1,2,3,4,5,6]
        distdf = pd.DataFrame(dist)
        for i in range(len(distdf)-1):
            res = distdf.loc[i].values==distdf.loc[i].values
            if True in res:
                print("true")
            else:
                print('no')   
        

        【讨论】:

        • 虽然您的解决方案可能会解决问题,但请解释为什么它可以使其更有效
        猜你喜欢
        • 1970-01-01
        • 2021-11-20
        相关资源
        最近更新 更多