是否有一些优雅的方式来操纵我的ndarray

Eas*_*sun 8 python numpy multidimensional-array

我有一个名为的矩阵xs:

array([[1, 1, 1, 1, 1, 0, 1, 0, 0, 2, 1],
       [2, 1, 0, 0, 0, 1, 2, 1, 1, 2, 2]])
Run Code Online (Sandbox Code Playgroud)

现在我想用同一行中最近的前一个元素替换零(假设第一列必须非零.).粗略的解决方案如下:

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]])
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激.

Bou*_*oud 2

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

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)
Run Code Online (Sandbox Code Playgroud)