代码之家  ›  专栏  ›  技术社区  ›  i.n.n.m

错误:序列的真值不明确-Python

  •  16
  • i.n.n.m  · 技术社区  · 9 年前

    我知道以前有人问过这个问题,然而,当我试图做一个 if 声明,我得到了一个错误。我看了这个 link dfs 是数据帧列表。

    for i in dfs:
        if (i['var1'] < 3.000):
           print(i)
    

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

    我尝试了以下操作,但得到了相同的错误。

    for i,j in enumerate(dfs):
        if (j['var1'] < 3.000):
           print(i)
    

    var1 数据类型为 float32 logical 运营商和 & | ValueError

    3 回复  |  直到 8 年前
        1
  •  14
  •   MaxU - stand with Ukraine    9 年前

    下面是一个小演示,展示了发生这种情况的原因:

    In [131]: df = pd.DataFrame(np.random.randint(0,20,(5,2)), columns=list('AB'))
    
    In [132]: df
    Out[132]:
        A   B
    0   3  11
    1   0  16
    2  16   1
    3   2  11
    4  18  15
    
    In [133]: res = df['A'] > 10
    
    In [134]: res
    Out[134]:
    0    False
    1    False
    2     True
    3    False
    4     True
    Name: A, dtype: bool
    

    当我们试图检查此类序列是否 True

    In [135]: if res:
         ...:     print(df)
         ...:
    ---------------------------------------------------------------------------
    ValueError                                Traceback (most recent call last)
    ...
    skipped
    ...
    ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
    

    解决方法:

    我们可以决定如何处理一系列布尔值-例如 if 应该返回 真的 如果 值为 :

    In [136]: res.all()
    Out[136]: False
    

    或者什么时候 值为True:

    In [137]: res.any()
    Out[137]: True
    
    In [138]: if res.any():
         ...:     print(df)
         ...:
        A   B
    0   3  11
    1   0  16
    2  16   1
    3   2  11
    4  18  15
    
        2
  •  4
  •   Gasvom    9 年前

    for i in dfs:
    if (i['var1'].iloc[0] < 3.000):
       print(i)
    

    series.iteritems

    for i in dfs:
        for _, v in i['var1'].iteritems():
            if v < 3.000:
                print(v)
    

    在大多数情况下,更好的解决方案是选择数据帧的子集用于您需要的任何内容,例如:

    for i in dfs:
        subset = i[i['var1'] < 3.000]
        # do something with the subset
    

    当使用串行操作而不是迭代单个值时,pandas在大数据帧上的性能要快得多。更多细节,你可以看看熊猫 documentation on selection.

        3
  •  2
  •   Shaina Raza    6 年前

         if((df[col] == ' this is any string or list').any()):
           return(df.loc[df[col] == temp].index.values.astype(int)[0])
    
    推荐文章