[Python] Incorrect Traceback on pandas ValueError [duplicate]

Discussão em 'Python' iniciado por Stack, Janeiro 23, 2025.

  1. Stack

    Stack Membro Participativo

    I saw some unexpected behavior during a ValueError when using pandas. When incorrectly using and instead of & to provide a boolean argument to a pandas series in a loop, the traceback points at the wrong line. Posting as a heads up to anyone else that may be mislead in a more complex script than the example below but also curious as to the underlying cause? Maybe I'm missing something here..

    import numpy as np
    import pandas as pd

    data = np.random.randint(0,10,size=(10,3))
    columns=['A','B','C']
    df = pd.DataFrame(data,columns=columns)

    for i in range(0,len(df)):
    a = df.loc[i,'A']
    brange = df[(df['B'] > 0) and (df['B'] < 4)]


    Traceback:

    ---------------------------------------------------------------------------
    ValueError Traceback (most recent call last)
    /var/folders/h0/nxt863516yb3cyz22ybjvvm80000gn/T/ipykernel_38164/2945067326.py in ?()
    8 import numpy as np
    9 import pandas as pd
    ---> 10
    11 data = np.random.randint(0,10,size=(10,3))
    12 columns=['A','B','C']
    13 df = pd.DataFrame(data,columns=columns)

    /opt/anaconda3/lib/python3.9/site-packages/pandas/core/generic.py in ?(self)
    1517 @final
    1518 def __nonzero__(self) -> NoReturn:
    -> 1519 raise ValueError(
    1520 f"The truth value of a {type(self).__name__} is ambiguous. "
    1521 "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
    1522 )

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


    pandas v. 2.1.4 python v. 3.9.18

    Continue reading...

Compartilhe esta Página