1

Im using str.startswith and if condition to 'do something' if the condition is TRUE. I have been browsing and kind of understand that for the if condition, it is unclear what to do with it. I not sure how exactly how to obtain the solution for my problem. The code I wrote first is:

for i in Bus.index:
    if (Bus['NAME'].str.startswith("S")) :
        print(i) 

This give me error:

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

I am trying to say:

for i in Bus.index:
    if rows in (Bus['NAME'].str.startswith("S")) are True, Then:
        print(i)
        and if it is false then do nothing.

As I understand it from the suggested post and other searches online, my problem does not have any use of the suggestions given in the error i get or can I see similar example( but I have less trained eye than many others, that could see my logical thinking error, and the keyword is in the beginning of the post

"I kinda understand" and "I not sure how exactly how to obtain the solution for my problem".

Thales
  • 37
  • 5
  • Please provide the entire error output, as well as a [mcve]. In any case, this seems to be a duplicate. – AMC Aug 19 '20 at 00:13
  • 1
    Does this answer your question? [Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()](https://stackoverflow.com/questions/36921951/truth-value-of-a-series-is-ambiguous-use-a-empty-a-bool-a-item-a-any-o) – AMC Aug 19 '20 at 00:14
  • @BEN_YO What answers are you referring to? It would probably be better to discuss something like this in a chat room, by the way. – AMC Aug 19 '20 at 00:28
  • @BEN_YO Unless I'm missing something, I can't see any answers to that question. – AMC Aug 19 '20 at 00:31
  • @BEN_YO Can you make a chatroom for this? – AMC Aug 19 '20 at 00:33

1 Answers1

0

I believe the if() is trying to evaluate the truthiness across all boolean values for all rows aggregately every time you loop, which is why the error is saying to wrap it in something like any() or all() to condense it down to a single boolean value.

Since you're looping through indices, you can use loc() to evaluate the row-value at each index as the loop progresses:

for i in Bus.index:
    if (Bus.loc[i, 'NAME'].startswith("S")):
        print(i) 

Depending on what you're using this for, you can also just return a list of the indices by subsetting the Bus df and avoid the for-loop altogether:

list(Bus[Bus['NAME'].str.startswith("S")].index)
mfnight
  • 108
  • 12