Adding row/column headers to NumPy arrays

后端 未结 5 1446
执笔经年
执笔经年 2020-12-29 03:59

I have a NumPy ndarray to which I would like to add row/column headers.

The data is actually 7x12x12, but I can represent it like this:

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-29 04:27

    I am not aware of any method to add headers to the matrix (even though I would find it useful). What I would do is to create a small class that prints the object for me, overloading the __str__ function.

    Something like this:

    class myMat:
        def __init__(self, mat, name):
            self.mat = mat
            self.name = name
            self.head = ['a','b','c','d','e','f']
            self.sep = ','
    
        def __str__(self):
            s = "%s%s"%(self.name,self.sep)
            for x in self.head:
                s += "%s%s"%(x,self.sep)
            s = s[:-len(self.sep)] + '\n'
    
            for i in range(len(self.mat)):
                row = self.mat[i]
                s += "%s%s"%(self.head[i],self.sep)
                for x in row:
                    s += "%s%s"%(str(x),self.sep)
                s += '\n'
            s = s[:-len(self.sep)-len('\n')]
    
            return s
    

    Then you could just easily print them with the headers, using the following code:

    print myMat(A,'A')
    print myMat(B,'B')
    

提交回复
热议问题