在 python 的 for 循环中绕过 ValueError

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

我正在尝试使用上面的函数来获取数据中任何姓名的出生人数,但只要有没有出现该姓名的年份,我的循环就会停止。在这种情况下,我得到了这个值错误:

---------------------------------------------------------------------------
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

我怎样才能绕过这个错误并让我的循环继续运行即使在我的数据中不包含给定 'name' 的年份?我弄乱了 tryexceptelsefinally 子句,但不知何故它打破了我的循环,只是 returns 0.

你没有展示你尝试过的东西,所以我不知道你到底错在哪里。但是,在循环中放置一个 try-except 块应该可以解决问题:

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()
            count = count + yearly
        except ValueError as e:
            print(f"Encountered error: {e}. Skipping.")
        
    return count

抱歉,我没有关于变量 female 的足够信息。

试试这个:

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

如果引发 ValueError,只需捕获它并 运行 下一次迭代。