AttributeError: 'float' object has no attribute 'isdigit' with no floats in the df

69 Views Asked by At

I am running the below bit of code and getting the subject error; however there are no floats in the data set I'm testing with right now (there are blanks), so not sure why it's throwing that error? Even more so when there is an else statement to handle the case when item.isdigit() is not True?

for item in df['Vehicle Number']:
    if item.isdigit():
        if item[0] == "0":
            df['Vehicle Number'] = df['Vehicle Number'].replace([item], item[1:4])
    elif re.search(pattern, item):  
        match = re.search(pattern, item)
        idx = match.span() # determine the start/finish of the pattern
        start = idx[0]+2
        end = idx[1]
            
        if item[start] == "0":
            df['Vehicle Number'] = df['Vehicle Number'].replace([item], item[start+1:end])
        else:
            df['Vehicle Number'] = df['Vehicle Number'].replace([item], item[start:end])
2

There are 2 best solutions below

3
TheHungryCub On BEST ANSWER

By converting the 'Vehicle Number' column to strings using .astype(str), you ensure that all values are treated as strings, and then you can apply string methods like .isdigit()

# Convert 'Vehicle Number' column to string
df['Vehicle Number'] = df['Vehicle Number'].astype(str)

pattern = r'\d{2}-\d{2}'  # Example pattern, change it according to your actual pattern

for item in df['Vehicle Number']:
    if item.isdigit():
        if item[0] == "0":
            df['Vehicle Number'] = df['Vehicle Number'].replace([item], item[1:4])
    elif re.search(pattern, item):  
        match = re.search(pattern, item)
        idx = match.span() # determine the start/finish of the pattern
        start = idx[0]+2
        end = idx[1]
            
        if item[start] == "0":
            df['Vehicle Number'] = df['Vehicle Number'].replace([item], item[start+1:end])
        else:
            df['Vehicle Number'] = df['Vehicle Number'].replace([item], item[start:end])
3
35308 On

Without the actual data causing this error it's hard to narrow down the problem. Nevertheless the method isdigit should be able to interpret floats, as that's the whole point of the method yet they must be in a string format (python documentation for isdigit) thus I'd recommend you cast item to a string (in case a single entry happens to be of say float type). I guess you should try if str(item).isdigit(): but again without the actual entries of df['Vehicle Number'] it's impossible to say definitively what the problem is.