NumPy - setting values ​​in a structured array based on other values ​​in a structured array

I have a structured array of NumPy:

a = numpy.zeros((10, 10), dtype=[ ("x", int), ("y", str)]) 

I want to set the values ​​to a["y"] or "hello" if the corresponding value in a["x"] negative. As far as I can tell, I should do it like this:

 a["y"][a["x"] < 0] = "hello" 

But that seems to change the values ​​in a["x"] ! What is the problem with what I'm doing, and how else should I do it?

+7
python numpy
source share
1 answer

First of all, in multi-level structured arrays, when you specify a data type as str numpy , it is assumed that this is 1 character string.

 >>> a = numpy.zeros((10, 10), dtype=[ ("x", int), ("y", str)]) >>> print a.dtype dtype([('x', '<i8'), ('y', 'S')]) 

As a result, the values ​​you enter are truncated to 1 character.

 >>> a["y"][0][0] = "hello" >>> print a["y"][0][0] h 

Therefore, use a data type like a10 , where 10 is the maximum length of your string.

Refer to this link for additional definitions for other data structures.

Secondly, your approach seems right to me.

Initiating a numpy structured array with int and a10 data types

 >>> a = numpy.zeros((10, 10), dtype=[("x", int), ("y", 'a10')]) 

Filling it with random numbers

 >>> a["x"][:] = numpy.random.randint(-10, 10, (10,10)) >>> print a["x"] [[ 2 -4 -10 -3 -4 4 3 -8 -10 2] [ 5 -9 -4 -1 9 -10 3 0 -8 2] [ 5 -4 -10 -10 -1 -8 -1 0 8 -4] [ -7 -3 -2 4 6 6 -8 3 -8 8] [ 1 2 2 -6 2 -9 3 6 6 -6] [ -6 2 -8 -8 4 5 8 7 -5 -3] [ -5 -1 -1 9 5 -7 2 -2 -9 3] [ 3 -10 7 -8 -4 -2 -4 8 5 0] [ 5 6 5 8 -8 5 -10 -6 -2 1] [ 9 4 -8 6 2 4 -10 -1 9 -6]] 

Applying your filtering

 >>> a["y"][a["x"]<0] = "hello" >>> print a["y"] [['' 'hello' 'hello' 'hello' 'hello' '' '' 'hello' 'hello' ''] ['' 'hello' 'hello' 'hello' '' 'hello' '' '' 'hello' ''] ['' 'hello' 'hello' 'hello' 'hello' 'hello' 'hello' '' '' 'hello'] ['hello' 'hello' 'hello' '' '' '' 'hello' '' 'hello' ''] ['' '' '' 'hello' '' 'hello' '' '' '' 'hello'] ['hello' '' 'hello' 'hello' '' '' '' '' 'hello' 'hello'] ['hello' 'hello' 'hello' '' '' 'hello' '' 'hello' 'hello' ''] ['' 'hello' '' 'hello' 'hello' 'hello' 'hello' '' '' ''] ['' '' '' '' 'hello' '' 'hello' 'hello' 'hello' ''] ['' '' 'hello' '' '' '' 'hello' 'hello' '' 'hello']] 

Checking a["x"]

 >>> print a["x"] [[ 2 -4 -10 -3 -4 4 3 -8 -10 2] [ 5 -9 -4 -1 9 -10 3 0 -8 2] [ 5 -4 -10 -10 -1 -8 -1 0 8 -4] [ -7 -3 -2 4 6 6 -8 3 -8 8] [ 1 2 2 -6 2 -9 3 6 6 -6] [ -6 2 -8 -8 4 5 8 7 -5 -3] [ -5 -1 -1 9 5 -7 2 -2 -9 3] [ 3 -10 7 -8 -4 -2 -4 8 5 0] [ 5 6 5 8 -8 5 -10 -6 -2 1] [ 9 4 -8 6 2 4 -10 -1 9 -6]] 
+5
source share

All Articles