8

という名前のマトリックスがありxsます:

array([[1, 1, 1, 1, 1, 0, 1, 0, 0, 2, 1],
       [2, 1, 0, 0, 0, 1, 2, 1, 1, 2, 2]])

ここで、ゼロを同じ行の最も近い前の要素に置き換えたいと思います (最初の列が非ゼロでなければならないと仮定します)。大まかな解決策は次のとおりです。

In [55]: row, col = xs.shape

In [56]: for r in xrange(row):
   ....:     for c in xrange(col):
   ....:         if xs[r, c] == 0:
   ....:             xs[r, c] = xs[r, c-1]
   ....: 

In [57]: xs
Out[57]: 
array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1],
       [2, 1, 1, 1, 1, 1, 2, 1, 1, 2, 2]])

どんな助けでも大歓迎です。

4

3 に答える 3

2

pandasを使用できる場合replace、1 つの命令で明示的に置換が表示されます。

import pandas as pd

import numpy as np

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


df = pd.DataFrame(a, dtype=np.float64)

df.replace(0, method='pad', axis=1)
于 2013-06-18T08:56:50.930 に答える
1

私のバージョンは、初期配列の段階的なローリングとマスキングに基づいており、追加のライブラリは必要ありません (numpy を除く):

import numpy as np

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

for i in xrange(a.shape[1]):
    a[a == 0] = np.roll(a,i)[a == 0]
    if not (a == 0).any():             # when all of zeros
        break                          #        are filled

print a
## [[1 1 1 1 1 1 1 1 1 2 1]
##  [2 1 1 1 1 1 2 1 1 2 2]]
于 2013-06-18T08:51:07.450 に答える
0

連続するゼロを計算する複雑なインデックス作成のトリックに夢中にならなくてもwhile、配列内の連続するゼロと同じ数だけ反復するループを作成できます。

zero_rows, zero_cols = np.where(xs == 0)
while zero_cols :
    xs[zero_rows, zero_cols] = xs[zero_rows, zero_cols-1]
    zero_rows, zero_cols = np.where(xs == 0)
于 2013-06-18T13:35:58.460 に答える