python - kwarg-splatting numpy 数组

标签 python numpy keyword-argument structured-array

如何编写一个包装类来实现此功能?

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

但是,尽管看起来像一本字典,延续不能被 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

请注意,数据帧已转置,因为 pandas 的主索引是列而不是行。

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

相关文章:

python - 从 Django 模型返回多个字段

Python:在任意维度中使用冒号运算符索引数组

python - 使 von Mises KDE 适应 Seaborn

Python wordcloud 颜色按词频

python - 类型错误 : XXXXX got an unexpected keyword argument 'XXXXXX'

python - 有没有办法干净地退出正在处理来自(永无止境的)生成器的数据的线程?

python - 将文件加载到字典时出现奇怪的python错误

python - 对如何使用 **kwarg 感到困惑

python - 如何检查for循环中的特定值然后结束它?

python - 关于 recarray 多字段索引的文档