0

I'm trying to compare the values from a two dimensional arrays within a nested for loop and I can't seem to get the right relational operation in this situation.

So I'm looping through two dimensional arrays and comparing its values to values in another one dimensional array and I'm having a really interesting day.

import numpy as np

packetsDb = np.empty((0,4))

head = [['AAA', 'BBB', 'CCC', 'DDD']]
packet1 = [[255, 256, 257, 258]]
packet2 = [[255, 256, 257, 259]]
test = [255, 256, 257, 259]


packetsDb = np.append(packetsDb, np.array(head), axis=0)
packetsDb = np.append(packetsDb, np.array(packet1), axis=0)
packetsDb = np.append(packetsDb, np.array(packet2), axis=0)

for x in packetsDb:
   for y in x:
       print(test[0], y, test[0] == y)

//Result
255 AAA False
255 BBB False
255 CCC False
255 DDD False
255 255 False //Whats happening here
255 256 False
255 257 False
255 258 False
255 255 False //and here
255 256 False
255 257 False
255 259 False
Ekeuwei
  • 273
  • 3
  • 7
  • 1
    You print test[**0**] and y in your example but you compare test[**2**] and y. There seems to be something wrong with these indices or I don't understand, what you want to show with these print-statements. – MangoNrFive Jul 01 '22 at 16:07
  • Yeah I was just testing something else to see what I was doing wrong and I didn't undo the code before posting it. However, I've updated the question, the problem persist. – Ekeuwei Jul 01 '22 at 16:15

1 Answers1

1

The result is indeed counter-intuitive at first, but it gets clearer once you print the types as well:

for x in packetsDb:
    for y in x:
        print(test[0], y, test[0] == y, type(test[0]), type(y))

//Result
255 AAA False <class 'int'> <class 'numpy.str_'>
...

test[0] and y look the same when printed, but they are in fact different types and thus the comparison resolves to False.

When you did append the string-list to the numpy-array numpy did cast the full array to a str-type including the integers to be able to represent the new data. See this link as a reference Python - strings and integers in Numpy array

MangoNrFive
  • 1,541
  • 1
  • 10
  • 23