1

Array is acting weirdly, I have this code:

a=np.array(['dfdfdfdf', 'gulf', 'egypt', 'hijazi a', 'gulf', 'egypt'])

And I did this:

a[0]="hello there my friend"

Result was:

array(['hello th', 'gulf', 'egypt', 'hijazi a', 'gulf', 'egypt'],
      dtype='<U8')

What exactly is going on?

John Sall
  • 1,027
  • 1
  • 12
  • 25

3 Answers3

1

The default dtype of an array of strings will be calculated based on the string with maximum length. In your case dtype='<U8'.

You'd have to define the dtype according to the length of the new string that you want to insert into the array.

You could do something like:

s = np.array(["hello there my friend"])
a = np.array(['dfdfdfdf', 'gulf', 'egypt', 'hijazi a', 'gulf', 'egypt'], \
              dtype=s.dtype) 

a[0] = "hello there my friend"

print(a)
array(['hello there my friend', 'gulf', 'egypt', 'hijazi a', 'gulf',
   'egypt'], dtype='<U21')
yatu
  • 86,083
  • 12
  • 84
  • 139
1

Read this.

a=np.array(['dfdfdfdf', 'gulf', 'egypt', 'hijazi a', 'gulf', 'egypt'], dtype = 'object')
Toni Sredanović
  • 2,280
  • 1
  • 11
  • 13
1

Change it by using dtype parameter to a very big number (e.g. 100):

>>> a=np.array(['dfdfdfdf', 'gulf', 'egypt', 'hijazi a', 'gulf', 'egypt'],dtype='<U100')
>>> a[0] = "hello there my friend"
>>> a
array(['hello there my friend', 'gulf', 'egypt', 'hijazi a', 'gulf',
       'egypt'], 
      dtype='<U100')
>>> 

Or use:

>>> a=np.array(['dfdfdfdf', 'gulf', 'egypt', 'hijazi a', 'gulf', 'egypt'],dtype='<U100')
>>> a.dtype = '<U100'
>>> a[0] = "hello there my friend"
>>> a
array(['hello there my friend', 'gulf', 'egypt', 'hijazi a', 'gulf',
       'egypt'], 
      dtype='<U100')
>>> 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114