pythonarraysvalueerror

Is there a way to replace a float element in an array with a string element in python?


I have two arrays in my code. One is a grid that is just filled with zero and the other is an array of characters with positions they need to be placed in on the grid. I included an image with my position array on the top and the grid on the bottom.

Arrays

I'm trying to fill in the grid given the characters positions. For example, I would write this

grid[0][0] = pos[0][0]

To place the character * on the top left. However it's giving me a value error

ValueError: could not convert string to float: '*'

I assume this is because the grid element is a float integer the position elements is a string. Is there any way around this?


Solution

  • Maybe there is a better way, I tried this:

    import numpy as np
    
    l =[['*',0,2],['C',1,0]]
    
    arr = np.array(l, dtype=object)
    
    alist = [(ord(i[0]), i[1], i[2]) for i in arr]
    arr_f = np.array(alist, dtype=float).reshape((1,6))
    print(arr_f)
    
    slist = [(chr(int(i[0])), int(i[1]), int(i[2]), chr(int(i[3])), int(i[4]), int(i[5])) for i in arr_f]
    print(np.array(slist, dtype=object).reshape((2,3)))
    

    Output:

    [[42.  0.  2. 67.  1.  0.]]
    [['*' 0 2]
     ['C' 1 0]]