2

I want to replace an element in a numpy array at a specific index. For example

   import numpy as np
   A = np.array([0,1,2,3,4,5,6])
   words = 'dan'
   tags = 'np'
   A[2] = words+"_"+tags

is giving me error:

   ValueError:could not convert string to float: 'dan_np

However, the desired effect should be:

     A =([0,1,'dan_np',3,4,5,6]

How do I achieve this ? Thank you

qwerty ayyy
  • 385
  • 1
  • 2
  • 19
  • 1
    Efficient numpy arrays are of uniform type; thus it's better to use a sentinel value, e.g. `[0, 1, -1, 3, 4]` for integers or `[0, 1, nan, 3, 4]` for floating point. The alternative to type entire array as object, but then you lose most of numpy magic. – Dima Tisnek Mar 15 '17 at 14:50
  • http://stackoverflow.com/questions/6701714/numpy-replace-a-number-with-nan for "replace element with nan at specific index" – Dima Tisnek Mar 15 '17 at 14:51
  • Your desired effect works with lists but not with NumPy arrays. NumPy arrays have a fixed dtype for every entry while in lists every entry can be of a different type. This rescriction of arrays makes their use faster, though. – Michael H. Mar 15 '17 at 14:54

2 Answers2

2

Convert to object dtype which would support mixed dtype data and then assign -

A = A.astype(object)
A[2] = words+"_"+tags

Sample run -

In [253]: A = np.array([0,1,2,3,4,5,6])

In [254]: A.dtype
Out[254]: dtype('int64')

In [255]: A = A.astype(object)

In [256]: A[2] = words+"_"+tags

In [257]: A
Out[257]: array([0, 1, 'dan_np', 3, 4, 5, 6], dtype=object)
Divakar
  • 218,885
  • 19
  • 262
  • 358
0

The error message, and comments, tell you that you can't put a string into an integer array.

You can how ever put a string into a list:

In [53]: Al = A.tolist()
In [54]: Al[2] = words+"_"+tags
In [55]: Al
Out[55]: [0, 1, 'dan_np', 3, 4, 5, 6]

And you can turn that list back into an array

In [56]: A = np.array(Al)
In [57]: A
Out[57]: 
array(['0', '1', 'dan_np', '3', '4', '5', '6'], 
      dtype='<U11')

Because of the mix of numbers and string np.array uses their common format - string. You could also specify object,and get the same result as @Divakar.

In [58]: A = np.array(Al, dtype=object)
In [59]: A
Out[59]: array([0, 1, 'dan_np', 3, 4, 5, 6], dtype=object)

Such an object array is similar to a list, containing pointers to elements elsewhere in memory.

If A should remain numeric, then you need to assign compatible numeric values.

hpaulj
  • 221,503
  • 14
  • 230
  • 353