Friday, 15 January 2010

Modify 2D Array (Python) -



Modify 2D Array (Python) -

hey guys have 2d array looks this:

12381.000 63242.000 0.000 0.000 0.000 8.000 9.200 0.000 0.000 12401.000 8884.000 0.000 0.000 96.000 128.000 114.400 61.600 0.000 12606.000 74204.000 56.000 64.000 72.000 21.600 18.000 0.000 0.000 12606.000 105492.000 0.000 0.000 0.000 0.000 0.000 0.000 45.600 12606.000 112151.000 2.400 4.000 0.000 0.000 0.000 0.000 0.000 12606.000 121896.000 0.000 0.000 0.000 0.000 0.000 60.800 0.000

(cut off couple of columns due formatting)

so indicates employee id, section id, followed 12 months worked each employee , hours worked each month. 2d array list of lists each row list in own. trying convert each nonzero value 1 , maintain zeros. there 857 rows , 14 columns. code follows:

def convbin(a): """nonzero values converted 1s , 0 values kept constant. """ in range(len(a)): j in range(len(a[i])): if a[i][j] > 0: a[i][j] == 1 else: a[i][j] == 0 homecoming

can tell me doing wrong?

you doing equality evaluation, not assignment, within loop:

a[i][j] == 1

should

a[i][j] = 1 # ^ note 1 equals sign

also, there no need return a; a beingness modified in-place, conventional implicitly return none removing explicit return ... line.

you should bear in mind that:

you don't want in else case; and iterating on range(len(...)) not pythonic - utilize e.g. enumerate.

your function hence simplified to:

def convbin(a): """convert non-zero values in 2-d array 1s.""" row in a: j, val in enumerate(row): if val: row[j] = 1

python arrays python-2.7

No comments:

Post a Comment