首页 > 解决方案 > 为什么这个函数没有正确调用?

问题描述

def func_list(l):
    t=list()
    z=list(l)
    for i in range(0,len(z)-1):

        if(z[i]==' '):continue
        a=z[i].split(':')
        if(a[0]==''): continue

        for j in range(i+1,len(z)-1):
            b=z[j].split(':')

            if(b[0]==' '): break
            if a[0]==b[0]:

                z[i]=z[i]+' '+b[1]
                z[j]=' '
            else:
                t.append(z[i])
                break

    return t

df_head['Message']=df_head['Message'].apply(func_list)

调用此函数时出现此错误

IndexError                                Traceback (most recent call last)
<ipython-input-41-d8f85a0144bf> in <module>
----> 1 df_head['Message']=df_head['Message'].apply(func_list)

~\Anaconda3\lib\site-packages\pandas\core\series.py in apply(self, func, convert_dtype, args, **kwds)
   3192             else:
   3193                 values = self.astype(object).values
-> 3194                 mapped = lib.map_infer(values, f, convert=convert_dtype)
   3195 
   3196         if len(mapped) and isinstance(mapped[0], Series):

pandas/_libs/src\inference.pyx in pandas._libs.lib.map_infer()

<ipython-input-40-00055f2d4f69> in func_list(l)
     14             if a[0]==b[0]:
     15 
---> 16                 z[i]=z[i]+' '+b[1]
     17                 z[j]=' '
     18             else:

IndexError: list index out of range

标签: pythonpandaslistfunction

解决方案


添加检查 b 的长度,然后使用 b[1] 进行下一个处理,例如

def func_list(l):
    t=list()
    z=list(l)
    for i in range(0,len(z)-1):

        if(z[i]==' '):continue
        a=z[i].split(':')
        if(a[0]==''): continue

        for j in range(i+1,len(z)-1):
            b=z[j].split(':')

            if(b[0]==' '): break
            if a[0]==b[0] and len(b)>1:

                z[i]=z[i]+' '+b[1]
                z[j]=' '
            else:
                t.append(z[i])
                break

    return t

推荐阅读