Home > Software design >  Convert string array into 2D numpy array
Convert string array into 2D numpy array

Time:10-19

I am sitting on a weird problem. I have two things, m and mhat:

m
    [[1 0 1 1 1 1 0 0 1 1 1 1 1 1 0 0 0 0 1 1 0 0 0 0 0 1 0 1 0 0 1 1 0 0 1 1
      0 0 0 0 1 1 1 0 1 0 0 0 0 0 0 0]
     [1 1 1 1 1 0 1 0 0 0 0 0 0 1 1 1 0 0 0 1 1 1 1 1 0 0 0 0 1 1 1 0 1 1 1 0
      0 1 1 0 1 1 1 1 1 0 0 1 1 1 0 0]]
    Mhat
    ['1' '1' '0' '1' '1' '1' '1' '1' '1' '1' '1' '0' '0' '1' '0' '0' '1' '0'
     '1' '0' '1' '0' '1' '0' '1' '0' '1' '1' '0' '1' '0' '1' '0' '0' '0' '0'
     '1' '0' '1' '1' '0' '1' '0' '1' '0' '1' '0' '1' '0' '0' '1' '0' '0' '0'
     '1' '0' '0' '1' '0' '1' '1' '1' '1' '0' '0' '1' '0' '1' '1' '1' '1' '0'
     '0' '0' '0' '1' '0' '1' '0' '0' '1' '1' '1' '1' '1' '1' '0' '1' '1' '1'
     '0' '0' '0' '0' '0' '1' '0' '1' '0' '1' '0' '0' '0' '0']

m is a numpy array if integers with n rows, while mhat is a numpy array with one dimension, full of strings. As one might see, in mhat, the elements are the same as in m, but with alternating indices. So, mhat[0] is the first element of the first row, mhat[1] the first element of the second row, mhat[2] the second one in the first, and so on.

I would like to convert mhat such that I can compare both of them. I have now like 30 lines of weird conversation with terrible performance and its still not correct, so I discarded it. Is there anybody here with an amazing idea for this?

CodePudding user response:

This should work:

l1 = [[1,2,3],[4,5,6]]
l2 = [1,4,2,5,3,6]


cols = 2
newl = [[] for x in range(cols)]
for i in range(int(len(l2)/cols)):
    for j in range(cols):
        newl[j].append(l2[i*cols   j])

I left out converting the strings to floats, but newl will be in the format of l1 and then you can go on to compare.

  • Related