1

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:

array([['2'],
       [''],
       [''],
       [''],
       [''],
       ['']], dtype='<U1')

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

1 Answer 1

2

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.