问题:用numpy构建一个基本的立方体?

我想知道numpy是否可用于构建最基本的立方体模型,其中存储所有交叉组合及其计算值。

让我们以以下数据为例:

AUTHOR         BOOK          YEAR        SALES
Shakespeare    Hamlet        2000        104.2
Shakespeare    Hamlet        2001        99.0
Shakespeare    Romeo         2000        27.0
Shakespeare    Romeo         2001        19.0
Dante          Inferno       2000        11.6
Dante          Inferno       2001        12.6

并且能够构建类似的东西:

                             YEAR                  TOTAL
AUTHOR            BOOK       2000       2001         
(ALL)             (ALL)      142.8      130.6      273.4
Shakespeare       (ALL)      131.2      118.0      249.2
Dante             (ALL)      11.6       12.6       24.2
Shakespeare       Hamlet     104.2      99.0       203.2
Shakespeare       Romeo      27.0       19.0       46.0
Dante             Inferno    11.6       12.6       24.2

我希望使用meshgrid之类的东西可以让我达到 75%。基本上,我想看看是否可以使用numpy(不是熊猫)构建所有预计算值的结构来构建结构,以便我可以检索所有可能组合的上述结果。为了简单起见,我们只考虑SUM作为唯一可能的计算。也许这是一种圆滑的询问方式,但是numpy可以成为这样做的支柱,还是我需要使用其他东西?

最后,如果在numpy中不可能,如何将其存储在 MDA 中?

解答

我认为numpyrecord arrays 可以用于此任务,下面是我基于记录数组的解决方案。

class rec_array():
    
    def __init__(self,author=None,book=None,year=None,sales=None):
        self.dtype = [('author','<U20'), ('book','<U20'),('year','<U20'),('sales',float)]
        self.rec_array = np.rec.fromarrays((author,book,year,sales),dtype=self.dtype)
        
    def add_record(self,author,book,year,sales):
        new_rec = np.rec.fromarrays((author,book,year,sales),dtype=self.dtype)
        if not self.rec_array.shape == ():
            self.rec_array = np.hstack((self.rec_array,new_rec))
        else:
            self.rec_array = new_rec
    
    def get_view(self,conditions):
        """
        conditions: 
            A list of conditions, for example 
            [["author",<,"Shakespeare"],["year","<=","2000"]]
        """
        mask = np.ones(self.rec_array.shape[0]).astype(bool)
        for item in conditions:
            field,op,target = item
            field_op = "self.rec_array['%s'] %s '%s'" % (field,op,target)
            mask &= eval(field_op)
        
        selected_sales = self.rec_array['sales'][mask]
        
        return np.sum(selected_sales)

基于这个rec_array,给定数据

author = 4*["Shakespeare"]+ 2*["Dante"]
book = 2*["Hamlet"] + 2*["Romeo"] + 2*["Inferno"]
year = 3*["2000", "2001"]
sales = [104.2, 99.0, 27.0, 19.0, 11.6, 12.6]

我们创建一个实例

test = rec_array()
test.add_record(author,book,year,sales)

例如,如果您想要销售莎士比亚的罗密欧,您可以简单地执行此操作

test.get_view([["author","==","Shakespeare"],["book","==","Romeo"]])

输出为 46.0

或者,您也可以这样做

test.get_view([["author","==","Shakespeare"],["year","<=","2000"]])

输出为 131.2

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐