numpy how to slice index an array using arrays?

2024/11/15 18:53:07

Perhaps this has been raised and addressed somewhere else but I haven't found it. Suppose we have a numpy array:

a = np.arange(100).reshape(10,10)
b = np.zeros(a.shape)
start = np.array([1,4,7])   # can be arbitrary but valid values
end = np.array([3,6,9])     # can be arbitrary but valid values

start and end both have valid values so that each slicing is also valid for a. I wanted to copy value of subarrays in a to corresponding spots in in b:

b[:, start:end] = a[:, start:end]   #error

this syntax doesn't work, but it's equivalent to:

b[:, start[0]:end[0]] = a[:, start[0]:end[0]]
b[:, start[1]:end[1]] = a[:, start[1]:end[1]]
b[:, start[2]:end[2]] = a[:, start[2]:end[2]]

I wonder if there is a better way of doing this instead of an explicit for-loop over the start and end arrays.

Thanks!

Answer

We can use broadcasting to create a mask of places to be edited with two sets of comparisons against start and end arrays and then simply assign with boolean-indexing for a vectorized solution -

# Range array for the length of columns
r = np.arange(b.shape[1])# Broadcasting magic to give us the mask of places
mask = (start[:,None] <= r) & (end[:,None] >= r)# Boolean-index to select and assign 
b[:len(mask)][mask] = a[:len(mask)][mask]

Sample run -

In [222]: a = np.arange(50).reshape(5,10)...: b = np.zeros(a.shape,dtype=int)...: start = np.array([1,4,7])...: end = np.array([5,6,9]) # different from sample for variety...: # Mask of places to be edited
In [223]: mask = (start[:,None] <= r) & (end[:,None] >= r)In [225]: print mask
[[False  True  True  True  True  True False False False False][False False False False  True  True  True False False False][False False False False False False False  True  True  True]]In [226]: b[:len(mask)][mask] = a[:len(mask)][mask]In [227]: a
Out[227]: 
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],[20, 21, 22, 23, 24, 25, 26, 27, 28, 29],[30, 31, 32, 33, 34, 35, 36, 37, 38, 39],[40, 41, 42, 43, 44, 45, 46, 47, 48, 49]])In [228]: b
Out[228]: 
array([[ 0,  1,  2,  3,  4,  5,  0,  0,  0,  0],[ 0,  0,  0,  0, 14, 15, 16,  0,  0,  0],[ 0,  0,  0,  0,  0,  0,  0, 27, 28, 29],[ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0],[ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0]])
https://en.xdnf.cn/q/71855.html

Related Q&A

How to import _ssl in python 2.7.6?

My http server is based on BaseHTTPServer with Python 2.7.6. Now I want it to support ssl transportation, so called https.I have installed pyOpenSSL and recompiled python source code with ssl support. …

Unexpected Indent error in Python [duplicate]

This question already has answers here:Im getting an IndentationError (or a TabError). How do I fix it?(6 answers)Closed 4 years ago.I have a simple piece of code that Im not understanding where my er…

pyshark can not capture the packet on windows 7 (python)

I want to capture the packet using pyshark. but I could not capture the packet on windows 7.this is my python codeimport pyshark def NetCap():print capturing...livecapture = pyshark.LiveCapture(interf…

How to get the Signal-to-Noise-Ratio from an image in Python?

I am filtering an image and I would like to know the SNR. I tried with the scipy function scipy.stats.signaltonoise() but I get an array of numbers and I dont really know what I am getting.Is there an…

Python and OpenCV - Cannot write readable avi video files

I have a code like this:import numpy as np import cv2cap = cv2.VideoCapture(C:/Users/Hilman/haatsu/drive_recorder/sample/3.mov)# Define the codec and create VideoWriter object fourcc = cv2.VideoWriter_…

Python as FastCGI under windows and apache

I need to run a simple request/response python module under an existing system with windows/apache/FastCGI.All the FastCGI wrappers for python I tried work for Linux only (they use socket.fromfd() and …

Scrapy shell return without response

I have a little problem with scrapy to crawl a website. I followed the tutorial of scrapy to learn how crawl a website and I was interested to test it on the site https://www.leboncoin.fr but the spide…

How to replace values using list comprehension in python3?

I was wondering how would you can replace values of a list using list comprehension. e.g. theList = [[1,2,3],[4,5,6],[7,8,9]] newList = [[1,2,3],[4,5,6],[7,8,9]] for i in range(len(theList)):for j in r…

Installed PySide but cant import it: no module named PySide

Im new to Python. I have both Python 2.7 and Python 3 installed. I just tried installing PySide via Homebrew and got this message:PySide package successfully installed in /usr/local/lib/python2.7/sit…

How to run SQLAlchemy on AWS Lambda in Python

I preapre very simple file for connecting to external MySQL database server, like below:from sqlalchemy import *def run(event, context):sql = create_engine(mysql://root:[email protected]/scraper?chars…