1

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 :)

2
  • Just a hint Series have a between method Commented Jan 16, 2022 at 14:36
  • @timgeb Would it be possible if you can evaluate or further explain it? I am kinda new to python Commented Jan 16, 2022 at 14:46

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yup, managed to solve it, thanks alot. Cheers!
0

Normally when I want to access data from an SQLite3 query and treat it like a dictionary I would do:

connection.row_factory = sqlite3.Row

1 Comment

Hi, ill read up on this, thanks for the hint ^^

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.