English 中文(简体)
如何支持NumPy ndarrays修改的数据解释?
原标题:How to support modified data interpretations in NumPy ndarrays?

我正试图书写一个包含NumPynp.ndarray中某些数据的3级的Salph。 然而,我希望我的班子也包含一个关于如何解释数据价值的信息。

例如,请在<代码>ndarray上的<>dcode>>>上加入np.float32,但还有一项“color修改这些浮动点值的含义。 因此,如果我想增加red number and a blue number,我必须首先将两个数字改为magenta,以便在法律上添加其基础_data阵列。 添加的结果将包含_color = “magenta”

这只是一例。 在现实中,“col”并不是一种扼杀(最好把它看作是一种 in),结果的“col”是由两个投入的“col”在数学上确定的,任何两个“col”之间的转换在数学上都有界定。

class MyClass:
    
    def __init__(self, data : np.ndarray, color : str):
        self._data = data
        self._color = color
    
    
    # Example: Adding red numbers and blue numbers produces magenta numbers
    def convert(self, other_color):
        if self._color == "red" and other_color == "blue":
            return MyClass(10*self._data, "magenta")
        elif self._color == "blue" and other_color == "red":
            return MyClass(self._data/10, "magenta")
    
    
    def __add__(self, other):
        if other._color == self._color:
            # If the colors match, then just add the data values
            return MyClass(self._data + other._data, self._color)
        else:
            # If the colors don t match, then convert to the output color before adding
            new_self = self.convert(other._color)
            new_other = other.convert(self._color)
            return new_self + new_other

我的问题是,<代码>_color 信息生命alongside。 因此,我似乎无法界定我的班子的明智指数化行为:

  • If I define __getitem__ to return self._data[i], then the _color information is lost.
  • If I define __getitem__ to return MyClass(self._data[i], self._color) then I m creating a new object that contains a scalar number. This will cause plenty of problems (for example, I can legally index that_object[i], leading to certain error.
  • If I define __getitem__ to return MyClass(self._data[i:i+1], self._color) then I m indexing an array to get an array, which leads to plenty of other problems. For example, my_object[i] = my_object[i] looks sensible, but would throw an error.

然后,我开始认为,我真正想要的是不同的“栏目”。 这样,指数值就会有“栏目”信息在<条码>d 类型上免费编码,但我不知道如何执行。

“col”的理论总数可能大约为10万。 然而,在任何单一文字执行中,使用率不到100。 因此,我认为可能维持一个名单/字典/字典? 在旧的“col子”中,以及它们如何规划有活力的产阶级......但灰色则倾向于以我不期望的方式冷静地改变类型,因此可能不是一条正确的道路。

All I know is that I don t want to store the "color" alongside every data value. The data arrays can be ~billions of entries, with one "color" for all entries.

我怎么能够追踪这种“col子”信息,同时还要有一个可以使用的类别?

问题回答

(__add__, 等) 从<条码>np.ndarray继承的可能性也大概是不可容忍的,对于相容的产阶级来说,这是可以做到的。

你们可以打破一小 wrap的 wrap子:

from typing import NamedTuple, Sequence, Any, Callable

import numpy as np

Colour = int
RED: Colour = 0x0000FF
MAGENTA: Colour = 0xFF00FF
BLUE: Colour = 0xFF0000


def common_colour(colours: Sequence[Colour]) -> Colour:
    # magic happens here
    return sum(colours)


class ColouredArray(NamedTuple):
    colour: Colour
    data: np.ndarray

    def __str__(self) -> str:
        return f ({self.colour}) {self.data} 

    def convert(self, new_colour: Colour) ->  ColouredArray :
        return ColouredArray(
            # magic happens here
            data=self.data * new_colour/self.colour,
            colour=new_colour,
        )


def all_common(arrays: Sequence[ ColouredArray ]) -> tuple[ ColouredArray ]:
    new_colour = common_colour([a.colour for a in arrays])
    return tuple(
        array.convert(new_colour) for array in arrays
    )


def call_common(method: Callable, *args, **kwargs) -> tuple[Colour, Any]:
    new_colour = common_colour([
        arg.colour
        for arg in (*args, *kwargs.values())
        if isinstance(arg, ColouredArray)
    ])
    return new_colour, method(
        *(
            arg.convert(new_colour).data if isinstance(arg, ColouredArray) else arg
            for arg in args
        ),
        **{
            k: arg.convert(new_colour).data if isinstance(arg, ColouredArray) else arg
            for k, arg in kwargs.items()
        },
    )


y = ColouredArray(*call_common(
    np.interp,
    x=ColouredArray(RED, np.arange(5)),
    xp=ColouredArray(RED, np.arange(1, 30, 2)),
    fp=ColouredArray(BLUE, np.arange(11, 40, 2)),
    left=-1,
))
print(y)

举例来说,<编码>查询-common的校对直接装入。 ColouredArray Constructionor 因为interp 返回单一np.ndarray。 在其他情况下,例如从<代码>numpy.linalg.lstsq返回的4-tuple,视需要由打电话者自行包装并重建一个彩色阵列。





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...