[SOLVED] string np array in python only takes the first letter of a value


In the following code, I want to add string "200" in the np array capacity.

import numpy as np
capacity = np.repeat("", 6).reshape((6, 1))
capacity[0, 0] = "200"

However the return result is always like:

       ['']], dtype='<U1')

Does anyone know the reason why it only takes the first letter(number)? and how to solve the problem?


that’s because of the dtype specified upon creation of the array.
<U1 – means that element is a char of length either 0, or 1. That’s why when you try to add a string of an arbitrary length only the first char is added.

So you need to specify the dtype to be an object if you want to work with any len strings:

>>> capacity = np.array(['' for x in range(6)], dtype='object')
>>> capacity[0] = "200"
>>> capacity
array(['200', '', '', '', '', ''], dtype=object)

Best of luck!

Answered By – Akado2009

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *