【问题标题】:Calculating column wise for a matrix using numpy in python在python中使用numpy为矩阵计算列
【发布时间】:2017-03-28 12:33:12
【问题描述】:

通过以下程序,我正在尝试计算每列的“0”、“1”、“2”和“3”的出现次数。该程序未按预期工作。我在某处读到应该对矩阵进行切片以计算出现列,但我不知道该怎么做。该程序是在 python 中使用 numpy 编写的。如何使用 numpy 做到这一点?

import numpy as np 
a=np.array([[ 2,1,1,2,1,1,2], #t1 is horizontal
[1,1,2,2,1,1,1],
[2,1,1,1,1,2,1],
[3,3,3,2,3,3,3],
[3,3,2,3,3,3,2],
[3,3,3,2,2,2,3],
[3,2,2,1,1,1,0]])
print(a)
i=0
j=0
two=0
zero=0
one=0
three=0
r=a.shape[0]
c=a.shape[1]

for i in range(1,r):
#print(repr(a))
for j in range(1,c):
    #sele=a[i,j]
    if (a[i,j]==0):
        zero+=1
    if (a[i,j]==1):
        one+=1
    if (a[i,j]==2):
        two+=1
    if (a[i,j]==3):
        three+=1
    if i==c-1:
        #print(zero)
        print(one)
        i+=0 
        j=j+1
        #print(two)
        #print(three)   
    i=i+1
    #print(zero)`

我也想按以下方式打印:

    column:         0 1 2 3 4 5 6
    occurrences:  0 0 0 0 0 0 0 1
                  1 1 3 2 2 4 3 1
                  2 2 1 3 4 1 2 2
                  3 4 3 2 1 2 2 2

【问题讨论】:

    标签: python numpy matrix


    【解决方案1】:

    这是使用列表功能的代码

    import numpy as np 
    inputArr=np.array([[ 2,1,1,2,1,1,2],
                    [1,1,2,2,1,1,1],
                    [2,1,1,1,1,2,1],
                    [3,3,3,2,3,3,3],
                    [3,3,2,3,3,3,2],
                    [3,3,3,2,2,2,3],
                    [3,2,2,1,1,1,0]
                    ])
    
    occurance = dict()
    toFindList = [0,1,2,3]
    for col in range(len(inputArr)):
        collist = inputArr[:, col]
        collist = (list(collist))
        occurance['col_' + str(col)] = {}
        for num in toFindList:
            occurcount = collist.count(num)
            occurance['col_' + str(col)][str(num)] = occurcount
    
    for key, value in occurance.iteritems():
        print key, value
    

    输出:

    col_2 {'1': 2, '0': 0, '3': 2, '2': 3}
    col_3 {'1': 2, '0': 0, '3': 1, '2': 4}
    col_0 {'1': 1, '0': 0, '3': 4, '2': 2}
    col_1 {'1': 3, '0': 0, '3': 3, '2': 1}
    col_6 {'1': 2, '0': 1, '3': 2, '2': 2}
    col_4 {'1': 4, '0': 0, '3': 2, '2': 1}
    col_5 {'1': 3, '0': 0, '3': 2, '2': 2}
    

    【讨论】:

      【解决方案2】:

      这应该会给你你想要的输出格式:

      def col_unique(a):
          return np.sum(np.dstack([np.in1d(a,i).reshape(a.shape) for i in np.unique(a)]), axis = 0).T
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-12-17
        • 1970-01-01
        • 1970-01-01
        • 2018-10-06
        • 1970-01-01
        • 1970-01-01
        • 2017-09-26
        • 1970-01-01
        相关资源
        最近更新 更多