0

I'm new to python and numpy and I wanted to create an array with mixed data types but I get this error :

>>> m = np.zeros((5,10))
>>> m[0,0] = 'e'

Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
m[0,0] = 'e'
ValueError: could not convert string to float: e

I'm using numpy beacuse it's easier to implement bigger sized arrays and edit them. I tried to change the data type of the array but I couldn't find any suitable one.

2
  • there is the dtype parameter. See this Commented Aug 21, 2017 at 11:42
  • 1
    Maybe you want to have a look at this part of the numpy documentation. Commented Aug 21, 2017 at 11:43

1 Answer 1

4
  1. If you really, really want an array with mixed data types, use dtype = object.

    m = np.zeros((5,10), dtype = object)
    
    m[0,0] = 'e'
    
    m
    Out[105]: 
    array([['e', 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=object)
    
  2. Now, you probably don't want that really, since object arrays are fairly useless and most numpy functions don't work with them. If you want to import a database into an array, for instance, you will want to use a Structured Array. This will let you mix strings and numbers in such a way that you can still do something with them via numpy

  3. If you really just want a way to deal with big databases using an efficient indexing scheme, you probably don't want numpy at all, but but instead want pandas or even dask. numpy is optimized for calculation, not storage.

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

1 Comment

I tried 'a2' as a type it worked too. I'm just trying to implement maze escaping algorithm and I wanted a "neater" way to represent the map instead of numbers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.