I am trying to create a function that calculates the total nr. of cars that pass a checkpoint at each specified speed (40,50, 60,...) km/h from a csv. file. I am a total novice in python and have not had much luck. I have tried to use different variations of for loops to extract the "Gällande Hastighet" (speed) column from the 2d list into a new list, but I am not allowed to use pandas. I have tried to use csv.reader and dictreader to append every 5th element into the new list but don't get any output. I have also tried using range. I have tried so many different alternatives and dont really know how to approach the question anymore. Any advice, resources, example code is appreciated.
The list looks like this:
[['MätplatsID', 'Gällande Hastighet', 'Hastighet', 'Datum', 'Tid'],
['14075010', '40', '55', '2021-09-11', '11:15:31'],
['14075010', '40', '54', '2021-09-11', '08:09:17'],
['14075010', '40', '53', '2021-09-11', '13:02:41'],
]
The end result should look like this: There are 69 measurements where the speed is 40 km/h
My rough code so far gives no output:
import csv
def number_of_cars(kamera_data):
with open('kameraData.csv', 'r', encoding = 'UTF-8') as csvfile:
csv_reader =list(csv.reader (csvfile, delimiter = ';'))
count = 0
for i in range(len(csv_reader)):
for j in range(len(csv_reader[i])):
count +=data[i][j]
print (count)
So, there is many ways to achieve what you need.
The CSV File:
MätplatsID,Gällande Hastighet,Hastighet,Datum,Tid
14075010,40,55,2021-09-11,11:15:31
14075010,40,54,2021-09-11,08:09:17
14075010,40,53,2021-09-11,13:02:41
14075010,41,53,2021-09-11,13:02:41
14075010,41,53,2021-09-11,13:02:41
14075010,44,53,2021-09-11,13:02:41
Using DictReader, you can read the csv file, iterate over the lines, and get the measured speed stored in another dict, where you can have multiple speeds.
After this, you just need to print each of the keys stored in this new dict.
Here is a example:
import csv
filename = 'carros.csv'
qty = 0
speeds = {}
with open(filename, 'r') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
# used the method .get() to get the existing value, or 0, if is the first speed
speeds[row['Gällande Hastighet']] = speeds.get(row['Gällande Hastighet'], 0) + 1
for k in speeds.keys():
print(f"There are {speeds[k]} measurements where the speed is {k} km/h.")
The result will be like this:
There are 3 measurements where the speed is 40 km/h.
There are 2 measurements where the speed is 41 km/h.
There are 1 measurements where the speed is 44 km/h.