代码之家  ›  专栏  ›  技术社区  ›  Tim Kirkwood

在多维numpy数组中查找非零索引

  •  1
  • Tim Kirkwood  · 技术社区  · 2 年前

    我有一个numpy数组,如下所示:

    np.array([
             [1, 0, 0.5, 1, 0],
             [0, 0, 0,   0, 0],
             [1, 0, 0,   1, 0]
            ])
    

    有人能提出获得一维索引数组的最快方法吗?其中,对于每个索引,数组中至少有一行的索引处有一个值>0?因此,对于上面的数组,所需的输出是(数据类型是什么并不重要,即列表与数组与系列等):

    [0, 2, 3]
    

    如果以上内容不清楚,请告诉我。目前,在我的真实用例中(如下),我从一个数据帧开始,转换为序列,转向numpy数组,获取非零索引,在这些索引处获取列。然而,我怀疑对数据帧进行一次操作(转换为numpy数组之后)会比 iterrows() 方法:

    df1 = pd.DataFrame([
                       [1, 0, 0.5, 1, 0],
                       [0, 0, 0,   0, 0],
                       [1, 0, 0,   1, 0]
                      ], 
                      columns = ['c1', 'c2, 'c3', 'c4', 'c5'], 
                      index = ['r1', 'r2', 'r3'])
    set1 = set()
    #This is what I would like to replace by going np.some_np_function(df1.to_numpy())
    for protein, row in df1.iterrows():  
        non_zero_indexes = list(row.to_numpy().nonzero()[0])
        columns_with_positive = [p for i,p in enumerate(row.index) if i in non_zero_indexes]
        set1.update(columns_with_positive)
    

    谢谢 蒂姆

    1 回复  |  直到 2 年前
        1
  •  2
  •   mozway    2 年前

    您可以使用:

    out = np.nonzero((a!=0).any(axis=0))[0]
    

    输出: array([0, 2, 3])

    使用您的数据帧:

    s = df1.ne(0).any()
    s.index[s]
    

    输出:

    Index(['c1', 'c3', 'c4'], dtype='object')