iQuaf
iQuaf

Reputation: 23

Grouping dates in python

I'm extremely new to python and I need to be able to do this without importing any modules. I have a csv file that contains Covid 19 data and I want to be able to calculate the mean, max etc for each given month and have those figures displayed in individual lists that are in chronological order. So far I have converted each line into a list and then I have been able to isolate the country from the input with this code `

  for line in datafile.readlines():
     column = line.split(",")
     if column[2] == country:

Then that outputs

['FRA', 'Europe', 'France', '11/07/2020', '364', '27\n'] ['FRA', 'Europe', 'France', '12/08/2020', '802', '28\n']
['FRA', 'Europe', 'France', '13/06/2020', '497', '24\n']
['FRA', 'Europe', 'France', '14/06/2020', '390', '10\n']

And I want to know how to divide these months up and then get the data for those months. So far I've tried to do the same as with the country but accessing the 3 element and splitting that by / but no success and also appending them to new empty lists but that also didnt work so help is much appreciated.

P.S: This also my first post on any type of forum or question site so please let me know if ive done anything wrong, thanks

Upvotes: 2

Views: 80

Answers (1)

Ilkyun Im
Ilkyun Im

Reputation: 129

I found that splitting using .split("/") works to me.

Here is an example:

month = {}
lists = [['FRA', 'Europe', 'France', '11/07/2020', '364', '27\n'], ['FRA', 'Europe', 'France', '12/08/2020', '802', '28\n'],
['FRA', 'Europe', 'France', '13/06/2020', '497', '24\n'],
['FRA', 'Europe', 'France', '14/06/2020', '390', '10\n']]

for element in lists :
    mon = element[3].split("/")[1]
    if mon not in month.keys():
        month[mon]= []
        month[mon].append(element)
    
    else :
        month[mon].append(element)

print(month)

The result is :

{'07': [['FRA', 'Europe', 'France', '11/07/2020', '364', '27\n']], '08': [['FRA', 'Europe', 'France', '12/08/2020', '802', '28\n']], '06': [['FRA', 'Europe', 'France', '13/06/2020', '497', '24\n'], ['FRA', 'Europe', 'France', '14/06/2020', '390', '10\n']]}

Upvotes: 1

Related Questions