Search code examples
pythonsqlpandasdataframeautomation

Pandas - single positional indexer is out-of-bounds


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?


Solution

  • Based on your question, I assume that blue can only show up exactly once or not at all.

    In this case you can just do:

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

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