How to assign string value to an array in numpy?

When I try to assign a string to an array as follows:

CoverageACol[0,0] = "Hello" 

I get the following error

 Traceback (most recent call last): File "<pyshell#19>", line 1, in <module> CoverageACol[0,0] = "hello" ValueError: setting an array element with a sequence. 

However, assigning integers does not result in an error:

 CoverageACol[0,0] = 42 

CoverageACol is a numpy array.

Please, help! Thanks!

+6
source share
2 answers

You get an error because the NumPy array is homogeneous, which means that it is a multi-dimensional table of elements of all the same type . This is different from a multidimensional list of lists in "regular" Python, where you can have objects of a different type in the list.

Normal Python:

 >>> CoverageACol = [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]] >>> CoverageACol[0][0] = "hello" >>> CoverageACol [['hello', 1, 2, 3, 4], [5, 6, 7, 8, 9]] 

Numpy:

 >>> from numpy import * >>> CoverageACol = arange(10).reshape(2,5) >>> CoverageACol array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) >>> CoverageACol[0,0] = "Hello" --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/biogeek/<ipython console> in <module>() ValueError: setting an array element with a sequence. 

So, it depends on what you want to achieve, why you want to save the string in an array filled for the rest with digits? If this is really what you want, you can set the data type of the NumPy array to a string:

 >>> CoverageACol = array(range(10), dtype=str).reshape(2,5) >>> CoverageACol array([['0', '1', '2', '3', '4'], ['5', '6', '7', '8', '9']], dtype='|S1') >>> CoverageACol[0,0] = "Hello" >>> CoverageACol array([['H', '1', '2', '3', '4'], ['5', '6', '7', '8', '9']], dtype='|S1') 

Note that only the first letter Hello is assigned. If you want the whole word to be assigned, you need to set an array type string :

 >>> CoverageACol = array(range(10), dtype='a5').reshape(2,5) >>> CoverageACol: array([['0', '1', '2', '3', '4'], ['5', '6', '7', '8', '9']], dtype='|S5') >>> CoverageACol[0,0] = "Hello" >>> CoverageACol array([['Hello', '1', '2', '3', '4'], ['5', '6', '7', '8', '9']], dtype='|S5') 
+13
source

You need to set the data type to array :

 CoverageACol = numpy.array([["a","b"],["c","d"]],dtype=numpy.dtype('a16')) 

This makes the ConerageACol array of strings (a) of length 16.

+4
source

Source: https://habr.com/ru/post/894656/


All Articles