NumPy - Set values in structured array based on other values in structured array

2024/10/7 12:27:59

I have a structured NumPy array:

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

I want to set values in a["y"] to either "hello" if the corresponding value in a["x"] is negative. As far as I can tell, I should be doing that like this:

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

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

Answer

First of all, in numpy structured arrays, when you specify datatype as str numpy assumes it to be a 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 get truncated to 1 character.

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

Hence use data type as a10, Where 10 being the max length of your string.

Refer this link, which specifies more definitions for other data structures.

Secondly your approach seems correct to me.

Inititating a structured numpy array with datatype int and a10

>>> 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']]

Verifying 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]]
https://en.xdnf.cn/q/70249.html

Related Q&A

numpy.disutils.system_info.NotFoundError: no lapack/blas resources found

Problem: Linking numpy to correct Linear Algebra libraries. Process is so complicated that I might be looking for the solution 6th time and I have no idea whats going wrong. I am on Ubuntu 12.04.5. I …

Opencv: Jetmap or colormap to grayscale, reverse applyColorMap()

To convert to colormap, I doimport cv2 im = cv2.imread(test.jpg, cv2.IMREAD_GRAYSCALE) im_color = cv2.applyColorMap(im, cv2.COLORMAP_JET) cv2.imwrite(colormap.jpg, im_color)Then,cv2.imread(colormap.jpg…

Get file modification time to nanosecond precision

I need to get the full nanosecond-precision modified timestamp for each file in a Python 2 program that walks the filesystem tree. I want to do this in Python itself, because spawning a new subprocess …

`TypeError: argument 2 must be a connection, cursor or None` in Psycopg2

I have a heroku pipeline set up, and have just enabled review apps for it. It is using the same codebase as my staging and production apps, same settings files and everything.When the review app spins …

replace string if length is less than x

I have a dataframe below. a = {Id: [ants, bees, cows, snakes, horses], 2nd Attempts: [10, 12, 15, 14, 0],3rd Attempts: [10, 10, 9, 11, 10]} a = pd.DataFrame(a) print (a)I want to able add text (-s) to …

Convert ast node into python object

Given an ast node that can be evaluated by itself, but is not literal enough for ast.literal_eval e.g. a list comprehensionsrc = [i**2 for i in range(10)] a = ast.parse(src)Now a.body[0] is an ast.Expr…

Keras custom loss function (elastic net)

Im try to code Elastic-Net. Its look likes:And I want to use this loss function into Keras:def nn_weather_model():ip_weather = Input(shape = (30, 38, 5))x_weather = BatchNormalization(name=weather1)(ip…

Django Models / SQLAlchemy are bloated! Any truly Pythonic DB models out there?

"Make things as simple as possible, but no simpler."Can we find the solution/s that fix the Python database world?Update: A lustdb prototype has been written by Alex Martelli - if you know a…

Fabric Sudo No Password Solution

This question is about best practices. Im running a deployment script with Fabric. My deployment user deploy needs sudo to restart services. So I am using the sudo function from fabric to run these com…

cartopy: higher resolution for great circle distance line

I am trying to plot a great circle distance between two points. I have found an in the cartopy docs (introductory_examples/01.great_circle.html):import matplotlib.pyplot as plt import cartopy.crs as cc…