2016-10-24 5 views
1

を満たしていない場合、私はスパース対称配列を持っていると私はその配列の行と列を削除しようとしています指定された行(および列)のすべての個々のエントリがある閾値条件を満たさない場合例えば削除行と列のすべての行の値(または列)が与えられたcontion

min_value = 2 
a = np.array([[2, 2, 1, 0, 0], 
       [2, 0, 1, 4, 0], 
       [1, 1, 0, 0, 1], 
       [0, 4, 0, 1, 0], 
       [0, 0, 1, 0, 0]]) 

私はそれは、少なくとも2以上の値となるよう、上記の例でこれが生じるであろうた行(および列)を保持したい場合

a_new = np.array([2, 2, 0], 
       [2, 0, 4], 
       [0, 4, 1]] 

すべてのエントリは、私が How could I remove the rows of an array if one of the elements of the row does not satisfy a condition?Delete columns based on repeat value in one row in numpy arrayDelete a column in a multi-dimensional array if all elements in that column satisfy a conditionを見て持っていたが、マークされたソリューションは、私が達成しようとしてる何合わない2.その後、小さいのでだから私は、行3と5(および列3と5)を失うことになります。

私は似たような行いを考えていた:

a_new = [] 
min_count = 2 

for row in a: 
    for i in row: 
     if i >= min_count: 
      a_new.append(row) 
    print(items) 
print(temp) 

が、それは悪い列を削除しませんので、これは動作しません。また、2つ(またはそれ以上)のインスタンスがある場合、値が大きい場合閾値はそれに複数回行を追加します。

答えて

1

下図のようにあなたはそれを解決するためのベクトル化ソリューションを持つことができます -

# Get valid mask 
mask = a >= min_value 

# As per requirements, look for ANY match along rows and cols and 
# use those masks to index into row and col dim of input array with 
# 1D open meshes from np.ix_ and thus select a 2D slice out of it 
out = a[np.ix_(mask.any(1),mask.any(0))] 

それはそうのように、行とそれから列を選択することによる表現する簡単な方法 -

a[mask.any(1)][:,mask.any(0)] 

入力配列の対称性を悪用すると、次のように簡略化されます。 -

mask0 = (a>=min_value).any(0) 
out = a[np.ix_(mask0,mask0)] 

サンプルラン - あるいは

In [488]: a 
Out[488]: 
array([[2, 2, 1, 0, 0], 
     [2, 0, 1, 4, 0], 
     [1, 1, 0, 0, 1], 
     [0, 4, 0, 1, 0], 
     [0, 0, 1, 0, 0]]) 

In [489]: min_value 
Out[489]: 2 

In [490]: mask0 = (a>=min_value).any(0) 

In [491]: a[np.ix_(mask0,mask0)] 
Out[491]: 
array([[2, 2, 0], 
     [2, 0, 4], 
     [0, 4, 1]]) 

は、我々はそうように、有効なマスクの行と列のインデックスを使用することができ -

r,c = np.where(a>=min_value) 
out = a[np.unique(r)[:,None],np.unique(c)] 

再び対称性を悪用し、簡略化バージョンは、希望こと -

r = np.unique(np.where(a>=min_value)[0]) 
out = a[np.ix_(r,r)] 

rは、ブール演算の組み合わせでも得られる可能性があります。

r = np.flatnonzero((a>=min_value).any(0)) 
+0

これは私が予想していたよりもはるかに雄弁です。これはそれほど重要ではありませんが、削除された行と列のリストを生成する方法はありますか? @Lukasz – Lukasz

+1

'np.flatnonzero(〜((A> = MIN_VALUE).ANY(0)))'? – Divakar

+0

は、空のリストを生成します。それは、特に大規模行列のための素晴らしいされているだろうが、私は、このリストを生成することはそれほど重要ではありません。 – Lukasz

関連する問題