Home > Mobile >  for-loop doesn't give the expected results
for-loop doesn't give the expected results

Time:09-17

I have a pretty simple for loop which doesn't give the expected results. It runs through a ndarray column row-by-row and should categorize e.g. the statements ' Heavy Vehicle' or ' Car' to numeric values (I know they are also strings).

for k in range(0, data.shape[0]):
    if data[k, 1] == ' Car' or ' Motorcycle' or ' Bicycle' or ' Pedestrian':
        data[k, 1] = '1'
    elif data[k, 1] == ' Heavy Vehicle' or ' Medium Vehicle' or ' Bus':
        data[k, 1] = '2'
    else:
        data[k, 1] = '3'

However the result is that python sets all values to '1' even those cells with the statement ' Heavy Vehicle'. I don't know why python doesn't replace the values with the defined numeric values.

Thanks in advance for your help!

CodePudding user response:

Try this:

data = np.array([[None]*3]*3)
data[:,1] = [' Car', ' Heavy Vehicle', 'CCC']
print(data)

for k in range(0, data.shape[0]):
    if any(x == data[k, 1] for x in [' Car', ' Motorcycle' , ' Bicycle' , ' Pedestrian']):
        data[k, 1] = '1'
    elif any(x == data[k, 1] for x in [' Heavy Vehicle', ' Medium Vehicle',' Bus']):
        data[k, 1] = '2'
    else:
        data[k, 1] = '3'
        
print(data)

Output:

[[None ' Car' None]
 [None ' Heavy Vehicle' None]
 [None 'CCC' None]]

[[None '1' None]
 [None '2' None]
 [None '3' None]]

CodePudding user response:

String are also boolean objects in Python!

You are basically doing False Or True, so True for each cycle.

Try this:

print(Bool(""))           # Empty String is False
print(Bool("String"))     # Full String is True

You should check string again, like:

for k in range(0, data.shape[0]):
    if data[k, 1] == ' Car' or data[k, 1] == ' Motorcycle' or data[k, 1] == ' Bicycle' or data[k, 1] == ' Pedestrian':
        data[k, 1] = '1'
    elif data[k, 1] == ' Heavy Vehicle' or data[k, 1] == ' Medium Vehicle' or data[k, 1] == ' Bus':
        data[k, 1] = '2'
    else:
        data[k, 1] = '3'

But I will personally write something like this:

moving_objects = [['Car','Motorcycle','Bicycle','Pedestrian'], 
                  ['Heavy Vehicle','Medium Vehicle','Bus']]

for k in range(0, data.shape[0]:
    data[k, 1] = [i if k in moving_objects[i][0] else 3 for i, m  in enumerate(moving_objects) ][0]

CodePudding user response:

The programm actually works as expected: the following statement ... or 'Motorcycle will always returns True because what you're doing is asking if 'Motorcycle': and if you do bool('Motorcycle) it will return True.

Therefore I suggest you refactor your code like shown below:

for k in range(0, data.shape[0]):
    _ = data[k, 1]
    if _ in [' Car', ' Motorcycle', ' Bicycle', ' Pedestrian']:
        data[k, 1] = '1'
    elif _ in [' Heavy Vehicle', ' Medium Vehicle', ' Bus']:
        data[k, 1] = '2'
    else:
        data[k, 1] = '3'
  • Related