为什么此函数调用不正确?

2024-04-19 12:42:55 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: inmessageconvertpandasdfleniflib
1条回答
网友
1楼 · 发布于 2024-04-19 12:42:55

添加对长度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

相关问题 更多 >