在将函数应用于numpy数组的每一行时,如何返回numpy数组而不是NoneType?

2024-04-25 05:43:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找到我的矩阵(511x511)中每一行的最小非零成对距离。但是,在我编写的以下代码中,我可以使用return函数获取第一行的值,也可以使用print函数获取所有行的值。你知道吗

我的代码:

def allmatch():
    Match = pd.DataFrame(squareform(pdist(m1, metric='braycurtis')),columns=df.Location_Index.unique(), index=df.Location_Index.unique())
    X = Match.values
    for row in X:
        i = np.where(row==np.min(row[np.nonzero(row)]))
        return(row[i])

In[1]: allmatch()
Out[1]: array([0.00917431])

或者

    def allmatch():
        Match = pd.DataFrame(squareform(pdist(m1, metric='braycurtis')),columns=df.Location_Index.unique(), index=df.Location_Index.unique())
        X = Match.values
        for row in X:
            i = np.where(row==np.min(row[np.nonzero(row)]))
            print(row[i])

In[2]: allmatch()
Out[2]: [0.00917431]
        [0.03496503 0.03496503]
        [0.01098901]
        [0.00346021]
        [0.00471698]
        [0.00316456]
        [0.01123596]
        ...(with 504 more values)

第一组代码返回numpy数组,第二组代码返回NoneType。我想以numpy数组的形式获得第二个集合中的值,有什么方法可以达到这个目的吗?我意识到我的代码可能不是解决这个问题的最有效的方法,如果有任何改进的建议,我将不胜感激。你知道吗


Tags: 函数代码dfindexreturndefmatchnp