如何获取numpy中每列的非零元素索引?

时间:2014-08-11 18:33:04

标签: python numpy indexing

我有一个矩阵

In [241]: coefs1
Out[243]: 
array([[  0.00000000e+00,   1.50237061e+00,   1.78732321e+00,
          3.07772735e+00,   3.07813831e+00,   3.10868249e+00,
          3.11535120e+00,   3.12940442e+00,   3.13184569e+00],
       [  0.00000000e+00,   0.00000000e+00,   2.47275798e-01,
          1.09915105e+00,   1.09941361e+00,   1.11107569e+00,
          1.10996973e+00,   1.11455077e+00,   1.11611816e+00],
       [  0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
          0.00000000e+00,   5.40736015e-04,   3.14102933e-02,
          2.94126207e-02,   3.73186676e-02,   3.98861164e-02],
       [  0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
          0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
          0.00000000e+00,  -5.68298896e-02,  -7.37245112e-02],
       [  0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
          1.89362500e+00,   1.89420071e+00,   1.92348705e+00,
          1.95920304e+00,   2.02228837e+00,   2.04170329e+00],
       [  0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
          0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
         -5.14869801e-02,  -1.09548801e-01,  -1.24983238e-01],
       [  0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
          0.00000000e+00,   0.00000000e+00,   3.69385511e-02,
          7.49599293e-02,   1.13349454e-01,   1.29144575e-01],
       [  0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
          0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
          0.00000000e+00,   0.00000000e+00,  -1.06357967e-02]])

我想为每列获取非0元素的索引。我希望显式的索引像[1,2,4]而不是[True,True,False,True]。

我尝试过类似的不同组合:

In [244]: np.apply_along_axis(lambda x: [i for i,val in enumerate(x) if val!=0], arr=coefs1, axis=0)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-253-f2fcb4de54a9> in <module>()
----> 1 np.apply_along_axis(lambda x: [i for i,val in enumerate(x) if val!=0], arr=coefs1, axis=0)

/usr/lib/python3/dist-packages/numpy/lib/shape_base.py in apply_along_axis(func1d, axis, arr, *args)
    115             i.put(indlist, ind)
    116             res = func1d(arr[tuple(i.tolist())],*args)
--> 117             outarr[tuple(i.tolist())] = res
    118             k += 1
    119         return outarr

ValueError: cannot copy sequence with size 2 to array axis with dimension 0

但我总是得到某种错误。 有这个问题的快速解决方案吗?

编辑:

解决方案,因为argwhere在1维数组上工作正常。

In [293]: np.argwhere(coefs1[:,2] != 0)
Out[293]: 
array([[0],
       [1]])

但是如何将此函数应用于矩阵的每一列? 好像我的专栏都是独立的载体。

1 个答案:

答案 0 :(得分:0)

没有内置处理这个,因为要返回一个数组,所有列必须具有相同数量的非零,这是一个非常特殊的情况。你可以做的最好的事情可能是:

[np.flatnonzero(row) for row in coefs1.T]