How to insert a letter inside matrix in Python?

Question:

I want to create an empty matrix and then insert letters inside.

s = np.zeros(2,3)
s[0,0]='A'

Output:

ValueError: could not convert string to float: 'A'

From my understanding matrix s only accepts numbers, so it rejects the string A. But is it possible to do it without complicated functions?

Asked By: Lee

||

Answers:

It can be done, just specify dtype=object:

s = np.zeros((2,3), dtype=object)
s[0,0]='A'
Answered By: code-lukas

There are some options, this depends on your use case so I explained 2 of those:


Just want an array of a type specifically

from the documentation, you should have read that you can specify dtype as a parameter in the np.zeros function; your type should be specified in the dtype parameter:

>>> zeros = np.zeros((2,3),dtype=str)
>>> zeros
array([['', '', ''],
       ['', '', '']], dtype='<U1')
>>> zeros[0,0] = 'A'
>>> zeros
array([['A', '', ''],
       ['', '', '']], dtype='<U1')

Just want a general option for all types?

Use dtype=object as it’s in use for general types.

Example
>>> zeros = np.zeros((2,3),dtype=object)
>>> zeros
array([[0, 0, 0],
       [0, 0, 0]], dtype=object)
>>> zeros[0,0] = "A"
>>> zeros
array([['A', 0, 0],
       [0, 0, 0]], dtype=object)

Some info from the docs:

The 24 built-in array scalar type objects all convert to an associated data-type object. This is true for their sub-classes as well.

Note that not all data-type information can be supplied with a type-object: for example, flexible data-types have a default itemsize of 0, and require an explicitly given size to be useful.

Useful links:

Answered By: XxJames07-

Using numpy arrays to store strings is not something that one would agree with. Or even do.

But if you really want and you think it is useful you can try this:

#writing full code btw:
s = numpy.array(0)
s = numpy.zeros(2, dtype=int)
s = numpy.array(list(map(list, "A")))
print(s)
Answered By: whitePawney
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.