Converting Data from string to Integer with if-else condition

I am trying to pull out the information from a table into a data frame and the next thing i wanted was to use an if-else statement based on data I retrieved and to insert it into a new column into the existing data frame.

q1 = c.execute('''
SELECT DISTINCT ontime.DayOfWeek,
   ontime.DayOfMonth AS DayOfMonthArrive,
   ontime.Month AS MonthArrive,
   ontime.Year AS YearArrive,
   ontime.DepTime AS DepTime, 
   AVG(ontime.DepDelay) AS avg_delay
FROM ontime
WHERE ontime.Cancelled = 0 AND 
   ontime.Diverted = 0 AND 
   ontime.DepDelay <= 0 AND 
   ArrDelay <= 0 
GROUP BY DepTime
ORDER BY avg_delay
''').fetchall()

^ How i pull out by data

conditions = [
(q1['DepTime'] >= 500) & (q1['DepTime'] <= 1159),
(q1['DepTime'] >= 1200) & (q1['DepTime'] <= 1800),
(q1['DepTime'] >= 1801) & (q1['DepTime'] <= 2359),
(q1['DepTime'] >= 0) & (q1['DepTime'] <=459)
]
values = ['Morning', 'Afternoon', 'Evening', 'Midnight']
q1['TimeOfTheDay'] = np.select(conditions, values)

However, I am currently facing this error. I have attempted quite a few steps but it just keeps on showing me the same error.

TypeError: list indices must be integers or slices, not str

Attempt 1:

q1['DepTime'] = pd.to_numeric(q1['DepTime'], errors='coerce')

Attempt 2:

q1['DepTime'] = q1['DepTime'].astype('int')

Would it be possible if anyone can help and point out the mistake I have made? Thanks in advance :)


Solution 1:

It seems that your variable q1 is a list and not a dataframe (i infered that was what you are going for haha) that's why you are getting a type error.