0

I wanted to learn a little bit more the handling of numpy arrays. I would like to have a nested loop through a 3D numpy array.

The result should look like:

2017-11-11, 1859
2017-11-12, 1359

I want would like to have as described as nested loop. My current loop looks like the following:

class Calculates(object):    
    def __init__(self, x, y):
        self.x = x
        self.y = y        
    def Calculator(self):
        calc = self.x*self.y

        return calc

playground = [['2017-11-11', 18, 17],
              ['2017-11-11', 16, 19],
              ['2017-11-11', 16, 19],
              ['2017-11-11', 20, 24],
              ['2017-11-11', 31, 15],
              ['2017-11-12', 10, 4],
              ['2017-11-12', 12, 3],
              ['2017-11-12', 15, 67],
              ['2017-11-12', 12, 23],
              ['2017-11-12', 1, 2]]   

for date, x, y in playground:
    print(date)
    calc = Calculates(x,y).Calculator()
    print(calc)

With this code I receive:

2017-11-11
306
2017-11-11
304
2017-11-11
304
2017-11-11
480
2017-11-11
465
2017-11-12
40
2017-11-12
36
2017-11-12
1005
2017-11-12
276
2017-11-12
2

I would like to have it in such a way for the for loop:

for date in playground:
    print(date)
    for x,y in playground:
        calc = Calculates(x,y).Calculator()
        print(calc)

to get the results described above.

but receive the following error message:

ValueError: too many values to unpack (expected 2)

0

1 Answer 1

1

You need to multiply values from the same date together and add them up; One way to do this is to aggregate the result using a dictionary with date as the key; here is an example using a defaultdict with zero as the default value:

from collections import defaultdict

# aggregate the result into d
d = defaultdict(int)
​
for date, x, y in playground:    
    calc = Calculates(x,y).Calculator()
    d[date] += calc
​
# print the dictionary
for date, calc in d.items():
    print(date, calc)
# 2017-11-11 1859
# 2017-11-12 1359
Sign up to request clarification or add additional context in comments.

Comments

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.