Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there some elegant way to manipulate my ndarray

I have a matrix named xs:

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

Now I want to replace the zeros by the nearest previous element in the same row (Assuming that the first column must be nonzero.). The rough solution as following:

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

Any help will be greatly appreciated.

like image 335
Eastsun Avatar asked Jun 18 '13 08:06

Eastsun


1 Answers

If you can use pandas, replace will explicitly show the replacement in one instruction:

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)
like image 172
Zeugma Avatar answered Oct 27 '22 09:10

Zeugma