I'm working on some code which looks like the following:

import numpy as np

A=np.array([[1,0,3,5,7],[4,0,6,2,3]])

def SMD(matrix):
if isinstance(matrix,np.ndarray)==False:
    raise ValueError('The needed datatype is an array')
else:
    m= matrix.shape[0]
    n= matrix.shape[1]
    a=np.array([])
    b=np.array([0])
    c=np.array([])
    for i in range(m):
        for j in range(n):
            if matrix[i][j] !=0:            
                np.append(a,matrix[i][j])
                np.append(c,j)
        np.append(b,len(a))
    return a,b,c

However, the numpy append does not work for me in this case. If I instead use lists instead of arrays, the code runs just fine:

def SMD(matrix):
if isinstance(matrix,np.ndarray)==False:
    raise ValueError('The needed datatype is an array')
else:
    m= matrix.shape[0]
    n= matrix.shape[1]
    d=[]
    e=[0]
    f=[]
    for i in range(m):
        for j in range(n):
            if matrix[i][j] !=0:  
                d.append(matrix[i][j])
                f.append(j)
        e.append(len(d))
    return d,e,f

the wanted output is:

[1, 3, 5, 7, 4, 6, 2, 3], [0, 4, 8], [0, 2, 3, 4, 0, 2, 3, 4]

Or as arrays (depending on the code used).

Of course, I would like to know why the first code is not working.

From my knowledge, it can be preferable in terms of computation speed to use arrays, but in this case, does it make a difference?

Thanks

推荐答案

In terms of efficiency you you should avoid loops

def SMD(matrix):
    bool_matrix = (matrix!=0)
    return (
        matrix[bool_matrix],
        np.append(0, bool_matrix.sum(1).cumsum()),
        np.where(bool_matrix)[1]
    )

SMD(A)
#(array([1, 3, 5, 7, 4, 6, 2, 3]),
# array([0, 4, 8]),
# array([0, 2, 3, 4, 0, 2, 3, 4]))

matrix[bool_matrix] are simply all the non-zero elements of matrix

np.append(0, bool_matrix.sum(1).cumsum()) first compute the number of non-zero elements in the rows of matrix; then it compute the cumulative sum (from the first row to the last one); finally it add the 0 at the beginning of the array.

np.where(bool_matrix)[1] tells you the indices of the columns in which the elements of matrix are non-zero.

Python相关问答推荐

如何使用OpenGL使球体遵循Python中的八样路径?

剪切间隔以添加特定日期

替换现有列名中的字符,而不创建新列

如果包含特定值,则筛选Groupby

在第一次调用时使用不同行为的re. sub的最佳方式

如何从数据框列中提取特定部分并将该值填充到其他列中?

正在try 让Python读取特定的CSV文件

如何获取给定列中包含特定值的行号?

在Pandas 中以十六进制显示/打印列?

极点:在固定点扩展窗口

对包含JSON列的DataFrame进行分组

使用Django标签显示信息

如何使用aiohttp获取图像并直接处理它而不保存它?

为列PANAS中的每个字符串值创建累计和列

我如何沿着我的图表绘制一条线来显示哪里的数据密度最高?

PYTHON中的regex与PostgreSQL等其他系统中的regex有区别吗?

在matplotlib中将标题的一部分设置为粗体和正常

用Arpeggio解析单行和多行注释

如果没有强制转换Numy数组,则通过ctype将Numy数组传递给C函数会产生错误的结果

如何添加脊椎箭头和偏移脊椎