gpt4 book ai didi

python - kwarg-splatting 一个 numpy 数组

转载 作者:太空宇宙 更新时间:2023-11-04 00:52:13 24 4
gpt4 key购买 nike

我怎样才能编写一个包装器类来实现这一点?

def foo(a, b):
print a

data = np.empty(20, dtype=[('a', np.float32), ('b', np.float32)])

data = my_magic_ndarray_subclass(data)

foo(**data[0])

更多背景:

我有一对这样的函数,我想对其进行矢量化:

def start_the_work(some_arg):
some_calculation = ...
something_else = ...

cost = some_calculation * something_else

return cost, dict(
some_calculation=some_calculation,
some_other_calculation=some_other_calculation
)

def finish_the_work(some_arg, some_calculation, some_other_calculation):
...

目的是用一堆不同的参数调用start_the_work,然后完成成本最低的项目。这两个函数使用了很多相同的计算,因此使用字典和 kwarg-splatting 来传递这些结果:

def run():
best, best_cost, continuation = min(
((some_arg,) + start_the_work(some_arg)
for some_arg in [1, 2, 3, 4]),
key=lambda t: t[1] # cost
)
return finish_the_work(best, **continuation)

我可以对它们进行矢量化的一种方法如下:

def start_the_work(some_arg):
some_calculation = ...
something_else = ...

cost = some_calculation * something_else

continuation = np.empty(cost.shape, dtype=[
('some_calculation', np.float32),
('some_other_calculation', np.float32)
])
continuation['some_calculation'] = some_calculation
continuation['some_other_calculation'] = some_other_calculation

return cost, continuation

但是尽管看起来像一本字典,continuation 不能用 kwarg-splatted。

最佳答案

这可能不是您想要的,但是将数组包装在 pandas DataFrame 中允许这样的事情:

import pandas as pd

def foo(a, b):
print(a)

data = np.empty(20, dtype=[('a', np.float32), ('b', np.float32)])

data = pd.DataFrame(data).T

foo(**data[0])
# 0.0

请注意,dataframe 是转置的,因为 pandas 的主索引是列而不是行。

关于python - kwarg-splatting 一个 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36638331/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com