pythonif-statementtry-catchexceptfinally

Bypassing ValueError in a for loop in python


def decade_total_count(decade, name):
    """
    sums up the number of births of the given 
    female baby `name` in a 10-year period
    
    Parameters:
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    decade ... starting year of the decade
    name   ... female name 
           ... str
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    """
    count = 0
    
    for i in range(decade, decade+10):
        yearly = females[(females['name']==name) & (females['year']==i)]['births'].item()
        count = count + yearly
        
    return count

I'm trying to use the function above to get the number of births for any name in the data but my loop stops whenever there's a year that the name does not occur in. In that case, I get this value error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/var/folders/yf/s14dt13x11n82t5kg4260v800000gn/T/ipykernel_4325/1603862037.py in <module>
----> 1 total_count('Jennifer')

/var/folders/yf/s14dt13x11n82t5kg4260v800000gn/T/ipykernel_4325/1143784105.py in total_count(name)
     42 
     43     for i in range(start, end, 10):
---> 44         counts.append(decade_total_count(i, name))
     45 
     46     return counts

/var/folders/yf/s14dt13x11n82t5kg4260v800000gn/T/ipykernel_4325/1143784105.py in decade_total_count(decade, name)
     15 
     16     for i in range(decade, decade+10):
---> 17         yearly = females[(females['name']==name) & (females['year']==i)]['births'].item()
     18         count = count + yearly
     19 

~/Desktop/anaconda3/lib/python3.9/site-packages/pandas/core/base.py in item(self)
    329         if len(self) == 1:
    330             return next(iter(self))
--> 331         raise ValueError("can only convert an array of size 1 to a Python scalar")
    332 
    333     @property

ValueError: can only convert an array of size 1 to a Python scalar

How can I bypass the error and keep my loop going even for years that does not contain the given 'name' in my data? I've messed around with try, except, else, and finally clause but somehow it breaks my loop and just returns 0.


Solution

  • Sorry but I don't have enough information about the variable female.

    Try this:

    def decade_total_count(decade, name):
        """
        sums up the number of births of the given 
        female baby `name` in a 10-year period
        
        Parameters:
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        decade ... starting year of the decade
        name   ... female name 
               ... str
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        """
        count = 0
        
        for i in range(decade, decade+10):
            try:
                yearly = females[(females['name']==name) & (females['year']==i)]['births'].item()
            except ValueError:
                continue
            count = count + yearly
            
        return count
    

    If a ValueError is raised, just catch it and run next iteration.