社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

在python中绕过for循环中的ValueError

vlaaaaaddd • 3 年前 • 1351 次点击  
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

我如何绕过这个错误,即使在数据中不包含给定的“名称”的年份,也能保持循环?我跟你搞砸了 try , except , else finally 子句,但不知怎的,它打破了我的循环,只返回0。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130603
 
1351 次点击  
文章 [ 2 ]  |  最新文章 3 年前
Sean Xie
Reply   •   1 楼
Sean Xie    3 年前

你还没有表现出你的努力,所以我不知道你到底出了什么问题。然而,在循环中放置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
Fed_Dragon
Reply   •   2 楼
Fed_Dragon    3 年前

抱歉,我没有足够的变量信息 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 被提出,只需捕捉它并运行下一个迭代。