Weird behaviour initializing a numpy array of string data

前端 未结 5 1607
挽巷
挽巷 2020-12-05 22:38

I am having some seemingly trivial trouble with numpy when the array contains string data. I have the following code:

my_array = numpy.empty([1, 2], dty         


        
5条回答
  •  长情又很酷
    2020-12-05 23:27

    Another alternative is to initialize as follows:

    my_array = np.array([["CAT","APPLE"],['','']], dtype=str)
    

    In other words, first you write a regular array with what you want, then you turn it into a numpy array. However, this will fix your max string length to the length of the longest string at initialization. So if you were to add

    my_array[1,0] = 'PINEAPPLE'
    

    then the string stored would be 'PINEA'.

提交回复
热议问题