2013-06-18 19 views
8

我有一个矩阵命名xs是否有操纵一些优雅的方式,我ndarray

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]]) 

任何帮助将不胜感激。

+1

你为什么认为你的解决方案不够优雅?只有我能想到的改进是从第二列开始循环,因为你有这个假设,它会为你节省一些操作;) –

+0

@jaux我想用一些ndarray的索引魔法来做到这一点。 python中循环的表现并不好。 – Eastsun

回答

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) 
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]] 
0

没有去疯狂与弄清楚连续零标组合技巧,你可以有一个while循环,也适用于尽可能多的迭代连续零有你array:

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) 
相关问题