I have a data and here has some date time.
like this:
datetime
2022-01-01
2022-02-01
2022-02-01
2022-03-01
2022-03-01
2022-03-01
2022-04-01
2022-04-01
2022-04-01
2022-04-01
2022-04-01
2022-04-01
2022-04-01
2022-04-01
2022-04-01
2022-05-01
2022-05-01
2022-05-01
2022-05-01
2022-05-01
2022-05-01
2022-05-01
2022-05-01
2022-05-01
2022-05-01
2022-05-01
2022-05-01
2022-05-01
2022-05-01
2022-05-01
I need to count monthly total so I do something like this
my code is:
df = pd.read_csv('example.csv')
example_per_month = []
for a in range(1,6):
example = {}
example[str(a)] = len(df[(df['datetime'] >= '2022-0' str(a) '-01')&(df['datetime'] <= '2022-0' str(a) '-31'))])
example_per_month.append(example)
print(example_per_month)
And her is my output:
[{'1':1},{'2':2},{'3':3},{'4':9},{'5':14}]
But I need the total count month by month now.
expected output:
[{'1':1},{'2':3},{'3':6},{'4':15},{'5':29}]
Thanks in advance
CodePudding user response:
this is not the exact solution you want but hope this will help you to find a solution
values = [{'1':10},{'2':20},{'3':30},{'4':9},{'5':14},{'6':37}]
loop = 1
total = 0
for val in values:
total = val[str(loop)]
val[str(loop)] = total
print(val[str(loop)])
loop = 1
print(total)
CodePudding user response:
"I need to count monthly total so I do something like this". I interpret this as meaning that the requirement is to count the number of dates that occur for any given month.
There is absolutely no need for heavyweight modules such as pandas for this.
FILENAME = 'foo.txt'
counter = {}
with open(FILENAME) as csv:
next(csv) # skip header
for line in csv:
mm = line[5:7].lstrip('0')
counter[mm] = counter.get(mm, 0) 1
print(counter)
Output:
{'1': 1, '2': 2, '3': 3, '4': 9, '5': 15}