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

如果您可以使用pandasreplace将在一条指令中明确显示替换:

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 回答