Home > other >  string np array in python only takes the first letter of a value
string np array in python only takes the first letter of a value

Time:03-21

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?

CodePudding user response:

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!

  • Related