How to replace a float element with a string in a zeroed array?

Asked

Viewed 100 times

2

I generated a zero matrix through the code:

import numpy as np
lista = np.zeros([4,4])

Later, I tried to replace an element of the matrix with some string (for example "a"). However, I made an error.

lista[0][0]="a"

How should I proceed?

  • 2

    It makes no sense that you have a heterogeneous matrix. Why you need to have zeros and strings in the same matrix?

1 answer

0

You have to define the type of the array you are creating so that it can accept a string, or a character: When setting the array type to S1, it will only save the first character of the string:

import numpy as np 

lista = np.zeros([4,4], dtype='|S1')
lista[0][0] = 'Aaaaa'

The result of the above code will be:

[['A' '' '' '']
 ['' '' '' '']
 ['' '' '' '']
 ['' '' '' '']]

If you want to save an entire String, you should set the value '|S5 to "dtype"':

import numpy as np 

lista = np.zeros([4,4], dtype='|S5')
lista[0][0] = 'Aaaaaa'

And the result will be:

[['Aaaaa' '' '' '']
 ['' '' '' '']
 ['' '' '' '']
 ['' '' '' '']]

Here is the documentation for these dtypes of a numpy matrix.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.