Home > Enterprise >  Pandas - single positional indexer is out-of-bounds
Pandas - single positional indexer is out-of-bounds

Time:07-06

I am trying to run an automation sql script in python and i want to export the results of the sql query. I used a code like this:

'''table1.loc[table1['colours'] == 'blue' ,'count'].iloc[0]'''

Basically, table1 is a 2*2 table with cols colours and count and here I want the count of blue. The query throws an error 'single positional indexer is out-of-bounds' and I see the reason is because blue doesn't exists in the table1. But this script will be run multiple time and we might or might not have blue at times. Can anyone help me with some kind of a case statement here?

CodePudding user response:

Going from your question, I assume that blue can only show up exactly once or not at all. In that case you could simply do:

table1.loc[table1['colours']=='blue', 'count'].sum()

If blue is not in the DataFrame, then it will return 0 and otherwise the count.

  • Related