Hey guys so I have a 2D array that looks like 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 to formatting)
So it indicates the employee ID, Department ID, followed by the 12 months worked by each employee and the hours they worked for each month. My 2D array is essentially a list of lists where each row is a list in its own. I am trying to convert each nonzero value to a one and maintain all the zeros. There are 857 rows and 14 columns. My code is as follows:
def convBin(A):
"""Nonzero values are converted into 1s and zero values are kept constant.
"""
for i in range(len(A)):
for j in range(len(A[i])):
if A[i][j] > 0:
A[i][j] == 1
else:
A[i][j] == 0
return A
Can someone tell me what I am doing wrong?
You are doing equality evaluation , not assignment , inside your loop:
A[i][j] == 1
should be
A[i][j] = 1
# ^ note only one equals sign
Also, there is no need to return A
; A
is being modified in-place, so it is conventional to implicitly return None
by removing the explicit return ...
line.
You should bear in mind that:
else
case; and range(len(...))
is not Pythonic - use eg enumerate
. Your function could therefore be simplified to:
def convBin(A):
"""Convert non-zero values in 2-D array A into 1s."""
for row in A:
for j, val in enumerate(row):
if val:
row[j] = 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.