Home > Blockchain >  While loop: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a
While loop: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a

Time:10-24

I've been reading about Pandas and trying to write some simple snippets. I've seen many people asking about the ValueError raised by Pandas but can't figure out how to accomplish the following: I have a simple dataframe:

Driver_Name Month/Year  Km_driven   Salaray
0   Ivaylo_Ivanov   Jan/21  2168    3208.64
1   Ivaylo_Ivanov   Feb/21  2350    3478.00
2   Ivaylo_Ivanov   Mar/21  3126    4626.48
3   Ivaylo_Ivanov   Apr/21  2415    3574.20
4   Ivaylo_Ivanov   May/21  2115    3130.20
5   Mihail Styanov  Jan/21  2678    3963.44
6   Mihail Styanov  Feb/21  3185    4713.80
7   Mihail Styanov  Mar/21  3280    4854.40
8   Mihail Styanov  Apr/21  3012    4457.76
9   Mihail Styanov  May/21  2980    4410.40
10  Petar_Petkov    Jan/21  2013    2979.24
11  Petar_Petkov    Feb/21  2089    3091.72
12  Petar_Petkov    Mar/21  2163    3201.24
13  Petar_Petkov    Apr/21  2098    3105.04
14  Petar_Petkov    May/21  2179    3224.92
15  Ivan_Ivanov Jan/21  2876    4256.48
16  Ivan_Ivanov Feb/21  2900    4292.00
17  Ivan_Ivanov Mar/21  2987    4420.76
18  Ivan_Ivanov Apr/21  3016    4463.68
19  Ivan_Ivanov May/21  2019    2988.12

I would like to have a while loop as follows:

while df['Driver_Name']=='Ivaylo_Ivanov':
        do something

I know that df['Driver_Name']=='Ivaylo_Ivanov' returns a boolean series, but why can't the while statement iterate over the boolean?

CodePudding user response:

You can do the following if you like to iterate through all rows:

for index, row in df.loc[df['Driver_Name'] == 'Ivaylo_Ivanov'].iterrows():
       do something

You are locating every row, where the condition is true and itarate through the rows.

You should'n use loops, if you have a large dataframe, thera are a many other ways.

Cheers!

CodePudding user response:

The while keyword expects a bool expression, not an array (series) of them. If you want to iterate over such series until you find a False, you could easily accomplish that with a simple for loop, or, as the Backtrace message suggests, using the member functions all, any, etc.

  • Related