python 字符串索引超出范围(一个函数对一个数据有效,但对另一个数据无效

python string index out of range (a function works on one data won't work on another

def start_with_num(data,col):
    """
    This function is to get the information of whether the title starts with numbers
    """

    num=[]
    for item in data[col]:
        if item[0].isdigit() == True:
            num.append(1)
        else:
            num.append(0)

    return num

这是我的代码,它在 2500 行火车数据上工作得很好

但是,当我将它实现到包含20,000个的测试数据时 给我一个错误,说字符串索引超出范围

功能是顺便统计一下有多少个数字开头的字符串

这是列上的样本数据

0    UK’s response to modern slavery leaving victim...
1                                         this is good
2    The "forgotten" Trump roast: Relive his brutal...
3                 Meet the happiest #dog in the world!
4    Tokyo's subway is shut down amid fears over an...
5               Ban lifted on Madrid doping laboratory
6    Despite the ‘Yuck Factor,’ Leeches Are Big in ...
7    #China and #Pakistan have cemented their polit...
8    Malls are dying, but it's hard to profit from ...
9    Filipino troops kill notorious Abu Sayyaf kidn...

您的数据中似乎有一个空字符串。您必须查找长度为:

的字符串
def start_with_num(data,col):
"""
This function is to get the information of whether the title starts with 
numbers
"""


num=[]
for item in data[col]:
    if len(item) > 0 and item[0].isdigit() == True:
        num.append(1)
    else:
        num.append(0)

return num