我有一个名为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]])
任何帮助将不胜感激。
最佳答案
如果可以使用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)
关于python - 有没有一些优雅的方法来操纵我的 ndarray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17164004/