Skip to content Skip to sidebar Skip to footer

Replace An Element In A Numpy Array At Specific Index

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] = word

Solution 1:

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)

Solution 2:

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.

Post a Comment for "Replace An Element In A Numpy Array At Specific Index"