I am trying to create a function that adds the values of the last 12 columns of a 2D array if the first item in each row matches another. The first element of each row represents the department ID number so I need a cumulative total of how many hours the employees of each department worked for each month. My 2D array is a list of lists and a sample of the data looks like this:
[[12606.0, 74204.0, 56.0, 64.0, 72.0, 21.6, 18.0, 0.0, 0.0],
[12606.0, 105492.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 45.6],
[12606.0, 112151.0, 2.4, 4.0, 0.0, 0.0, 0.0, 0.0, 0.0],
[12606.0, 121896.0, 0.0, 0.0, 0.0, 0.0, 0.0, 60.8, 0.0]]
My code is as follows:
def costcentersum(A):
"""Finds the sum of the monthly hours worked by employees in each cost center.
"""
for i in range(len(A)):
if A[i-1][0] == A[i][0]:
A[i][2:] += A[i-1][2:]
print A[i]
My output though is rather strange and is not the correct answer. I got this:
[12606.0, 121896.0, 0.0, 0.0, 0.0, 0.0, 0.0, 60.8, 0.0, 0.0, 0.0, 8.0, 15.2, 18.4, 2.4, 4.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 45.6, 32.0, 54.4, 52.0, 56.0, 43.2, 56.0, 64.0, 72.0, 21.6, 18.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
I want my output to not include the second column of the data (the employee ID). Just simply the dep ID and the cumulative hours for each month. Where am I going wrong in my code? Thanks for any help!