0

I am trying to insert a string into a integer based matrix in numpy matrix. I am wondering if their is a way to change the datatype of the index that I want to store the string in?

I have tried to use the .astype() function but had no luck in doing so. This is what I have tried to do

c = np.array([0])
c.resize((3,3))
c.fill(0)
c.astype(str)
c.itemset(2, 0, 'S')
This is what I am trying to have my output look like:    

     OutPut:
    [[0 0 S]
    [0 0 0]
    [0 0 0]]

2 Answers 2

2

You need to set the dtype to object in order to allow multiple data types inside an array:

c = np.array([0])
c.resize((3,3))
c.fill(0)
c = c.astype('O')
c.itemset(2, 0, 'S')
c
>> array([[0, 0, 0],
       [0, 0, 0],
       ['S', 0, 0]], dtype=object)

Sidenote: numpy arrays are not meant to be multiple type and this will likely be underperformant

Sign up to request clarification or add additional context in comments.

Comments

0

Make your c (a simpler way):

In [377]: c = np.zeros((3,3), int)                                                                              
In [378]: c                                                                                                     
Out[378]: 
array([[0, 0, 0],
       [0, 0, 0],
       [0, 0, 0]])

Trying assign a string to an integer dtype results in an error - it can't convert the string to an integer:

In [379]: c[0,2] = 'S'                                                                                          
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-379-d41cf66ff6a1> in <module>
----> 1 c[0,2] = 'S'

ValueError: invalid literal for int() with base 10: 'S'

astype does not work in-place:

In [380]: c.astype(str)                                                                                         
Out[380]: 
array([['0', '0', '0'],
       ['0', '0', '0'],
       ['0', '0', '0']], dtype='<U21')
In [381]: c                                                                                                     
Out[381]: 
array([[0, 0, 0],
       [0, 0, 0],
       [0, 0, 0]])

Make a new array with the string dtype:

In [382]: c1 = c.astype(str)       

Now we can assign the new string value:

In [383]: c1[0,2] = 'S'                                                                                         
In [384]: c1                                                                                                    
Out[384]: 
array([['0', '0', 'S'],
       ['0', '0', '0'],
       ['0', '0', '0']], dtype='<U21')

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.