3D Numpy数组嵌套循环Python

时间:2018-02-04 22:40:33

标签: python loops numpy nested-loops

我想学习更多关于numpy数组的处理。我想通过3D numpy数组进行嵌套循环。

结果如下:

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

我想要像嵌套循环一样描述。我当前的循环如下所示:

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)

使用此代码我收到:

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

我想以这种方式使用for循环:

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

获得上述结果。

但收到以下错误消息:

  

ValueError:解压缩的值太多(预期2)

1 个答案:

答案 0 :(得分:1)

您需要将同一日期的值相乘并加起来;一种方法是使用带有 date 的字典作为键来聚合结果;这是一个使用defaultdict并将零作为默认值的示例:

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