3D Numpy 数组嵌套循环 Python
3D Numpy Array Nested Loop Python
我想多学习一点 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: too many values to unpack (expected 2)
您需要将同一日期的值相乘并相加;一种方法是使用以 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
我想多学习一点 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: too many values to unpack (expected 2)
您需要将同一日期的值相乘并相加;一种方法是使用以 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