考虑以下代码:
正如您所看到的,
我需要做的是允许
我想到的唯一方法是在
然而,我需要在与
最终结果将类似于这样:
有什么想法可以帮我完成这个任务吗?
class MyClass(object):
def __init__(self):
self.data_a = np.array(range(100))
self.data_b = np.array(range(100,200))
self.data_c = np.array(range(200,300))
def _method_i_do_not_have_access_to(self, data, window, func):
output = np.empty(np.size(data))
for i in xrange(0, len(data)-window+1):
output[i] = func(data[i:i+window])
output[-window+1:] = np.nan
return output
def apply_a(self):
a = self.data_a
def _my_func(val):
return sum(val)
return self._method_i_do_not_have_access_to(a, 5, _my_func)
my_class = MyClass()
print my_class.apply_a()
_method_i_do_not_have_access_to
方法接受一个numpy数组、一个窗口参数和一个用户定义的函数句柄,并返回一个包含函数句柄在输入数据数组中每次window
数据点上输出值的数组——这是一种通用的滚动方法。我无法更改此方法。正如您所看到的,
_method_i_do_not_have_access_to
将一个输入传递给函数句柄,该输入是传递给_method_i_do_not_have_access_to
的数据数组。该函数句柄仅根据传递给它的一个数据数组上的window
数据点计算输出。我需要做的是允许
_my_func
(传递给_method_i_do_not_have_access_to
的函数句柄)在data_b
和data_c
上操作,除了通过_method_i_do_not_have_access_to
传递给_my_func
的数组之外,在相同的window
索引处操作。data_b
和data_c
在MyClass类
中全局定义。我想到的唯一方法是在
_my_func
中包含对data_b
和data_c
的引用,就像这样:def _my_func(val):
b = self.data_b
c = self.data_c
# do some calculations
return sum(val)
然而,我需要在与
_method_i_do_not_have_access_to
传递的长度为window
的数组的切片val
相同的索引处对b
和c
进行切片。
例如,如果_method_i_do_not_have_access_to
中的循环当前在输入数组的索引45 -> 50
上运行,则_my_func
必须在b
和c
上以相同的索引进行操作。最终结果将类似于这样:
def _my_func(val):
b = self.data_b # somehow identify which slide we are at
c = self.data_c # somehow identify which slide we are at
# if _method_i_do_not_have_access_to is currently
# operating on indexes 45->50, then the sum of
# val, b, and c should be the sum of the values at
# index 45->50 at each
return sum(val) * sum(b) + sum(c)
有什么想法可以帮我完成这个任务吗?
_method_i_do_not_have_access_to
似乎只针对输入数组的最后一维进行计算。这就是为什么我得出的结论是唯一的解决方案是将全局数组传递到my_func
中并在其中进行切片。对于简洁的回答加1。 - Jason Strimpel