''float' object is not subscriptable error when using pandas to extract data from cell

I am importing a CSV file and I want to look at the school_hours column and extract the starting hours. Here are the first few lines from the column (you can assume that the data is already imported)

Essentially, I want to create a new column named starting_hours that should look something like this:

This is the following code that I wrote:

df['starting_hours']= [i[0:5] for i in df.School_Hours.str.split(' ').values]

I keep getting a 'float' object is not subscriptable error



Solution 1:[1]

You can try str.split then access the first element of list with str[0]

df['starting_hours'] = df['School_Hours'].str.split('-').str[0].str.strip('AM|PM')
print(df)

      School_Hours starting_hours
0  08:00AM-O3:00PM          08:00

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ynjxsjmh