Tips for combining two numpy ndarrays together without the concatenate function

I'm currently coding with Numba to JIT compile my Python code. My function takes two arrays of the same length as input, randomly selects a slicing point, and then returns a tuple containing two "Frankenstein" arrays created from parts of the two input strings. Unfortunately, Numba does not yet support the numpy.concatenate function (and it's unclear if it ever will). Since I am not willing to part ways with Numpy, I am in search of a performant solution for concatenating two Numpy arrays without using the concatenate function.

def randomSlice(str1, str2):
    lenstr = len(str1)
    rnd = np.random.randint(1, lenstr)
    return (np.concatenate((str1[:rnd], str2[rnd:])), np.concatenate((str2[:rnd], str1[rnd:])))

Answer №1

Perhaps this solution could be useful for your situation:

import numpy as np
import numba as nb

@nb.jit(nopython=True)
def randomSlice_nb(str1, str2):
    lenstr = len(str1)
    rnd = np.random.randint(1, lenstr)

    out1 = np.empty_like(str1)
    out2 = np.empty_like(str1)

    out1[:rnd] = str1[:rnd]
    out1[rnd:] = str2[rnd:]

    out2[:rnd] = str2[:rnd]
    out2[rnd:] = str1[rnd:]
    return (out1, out2)

In my testing environment, utilizing Numba 0.27 and measuring performance with the timeit module to ensure accurate timings without including compilation time, the Numba implementation shows a minor yet noticeable improvement in speed when processing arrays of integers or floating-point numbers with various sizes. However, it is noteworthy that if the arrays have a data type like |S1, the Numba version performs notably slower. This can be attributed to Numba's focus on optimizing numerical computations rather than non-numeric scenarios. Since I lack precise details regarding the structure of your input arrays str1 and str2, I cannot guarantee the code will cater perfectly to your specific requirements.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: The `math.sqrt()` function encountered a math domain error due to an invalid value

Can anyone help me with a program to check for Herone Triangle in the specified range of tries to max_tries? I'm having trouble with the math.sqrt() function. This is the code I have so far: import math max_tries = 10000 tries = 1 half_perimeter = ( ...

Python may not always accurately detect function loop conditions

I have the following Python code snippet: def numTest(): getNum = "https://sms-activate.ru/stubs/handler_api.php?api_key=" + api + "&action=getNumber&service=go&country=3" numReq = requests.get(getNum) smsNum = n ...

Creating a Virtual Environment via Command Line: Step-By-Step Guide

On my computer, I have both Python 3.11.4 and the latest version, Python 3.12, installed. However, I only provided the path for 3.12 in the system environment variables during installation (I unchecked the "Add Python 3.11 to PATH" option). I now need to ...

Delaying between typed characters in Selenium SendKeys can be achieved by implementing a small pause

I have encountered an issue while using an actions chain to input text, where duplicate characters appear. I suspect this might be due to the lack of delay. How can I fix this problem? Here is an example code snippet: big_text = "Lorem ipsum dolor sit ...

Keep looping for printing screenshots

Looking for some assistance. I have a Python script that loads URLs and takes screenshots. Here's what I'm trying to accomplish: Instead of using an array, read URLs from a text file Take individual screenshots of each loaded URL and save them ...

Guide to effectively deleting a Django object instance using Ajax

In the HTML, a list has been generated representing all objects (Cards). Currently, there is a delete button that uses Django functionality, but it requires a page reload to take effect. Is it possible to integrate AJAX into this program easily? Being new ...

When the start_time metadata is set to 0, the MP3 loading function in librosa returns an empty dataset

I am facing an issue with loading my dataset of bird chirps audio files (mp3) using librosa.load() Even though the MP3 files are being loaded, most of the time I end up with an empty np.ndarray instead of one filled with floats To investigate, I utilized ...

The result from a bitwise shift operation is inaccurate

As I am completing my Informatics assignment, here is the question I have constructed: Define a variable s with a value of 154 and a variable p with a value of 6. Showcase their values in both decimal and binary formats on the screen. s=154 p=6 bs=bin(s) ...

Error: The specified element is not found in the list when attempting to remove it, although it actually exists within the

I am currently going through the O'Reilly book "Exploring Everyday Things in R and Ruby" and my task is to convert all of the Ruby code into Python. I started with a model that determines the number of bathrooms required for a building, and here' ...

Attempting to utilize a Python 3 web scraping tool

Having trouble creating a web scraper for the first time. The script is failing to run and displaying an error code. The tutorial I followed can be found at: Despite following all steps and watching other YouTube tutorials for additional guidance, none o ...

Using an `if else` statement to verify various conditions with only one input of text

I am experimenting with a modified version of the classic 3-Cup Monte Program. Students are using Brython in CodeHS Ide to create a game where they draw "cups" and randomly place a white ball under one of them. The drawing part is working perfectly fine. H ...

Achieve visibility on the latest window using Selenium WebDriver in Python

After successfully clicking on a button that triggers the opening of a new browser window with Selenium Webdriver in Python, I'm faced with the challenge of shifting the focus to this newly opened window. Despite thorough internet searches, the lack o ...

Change the datetime string format to display the month using three letters

Is there a way to read/convert datetime strings like 2004 06 01 00 01 37 600 using the following code: df = pd.read_fwf('test.dat', widths=[25]) dates = pd.to_datetime(df.ix[:,0], format='%Y %m %d %H %M %S %f') print dates which res ...

Python code for searching XML elements with namespaces using XPath queries with specific tags and attributes

It seems like I must be missing something fundamental here, as every example I find and read on SO suggests that this should work. My goal is to utilize an XPath search with the lxml etree library to extract information from a Garmin TCX file: <?xml v ...

determines the highest value in a column for a specific date

Is it possible to find the maximum sum column value for the date "2018 Jan" and return columns A, a, b, c with just one concise line of code? Date A sum a b c d 0 2018-01-19 user1 1.82 -0.2 ...

Improving performance of bigint operations

I've been working through the book 'Programming in D' to learn about the D programming language. Recently, I attempted to tackle a problem involving summing up the squares of numbers from 1 to 10000000. Initially, I employed a functional app ...

What is the method for using a Python turtle to illustrate the Collatz sequence as a line graph?

def generate_sequence(number): if number <= 0: print("Zero or negative numbers are not even, nor Odd.", "Enter number >", number) else: print(int(number)) while number != 1: #number is e ...

serving up an HTML document through Django following user interaction

I'm facing a challenge with my HTML tables that I extract from a third-party program. I want to display these tables without relying on JavaScript. The goal is for the user to see 4 categories, each containing multiple options. However, only one item ...

Sharing values between PHP and Python: A guide to passing input data

Currently, I am utilizing a Pepper Robot to capture photos for object detection using the coco_classes with a yolov3 algorithm located on my Windows 10 computer. To facilitate object selection for recognition, I built an app for the Pepper Tablet using res ...

How to extract information from a shared notebook on Evernote using Python

Trying to retrieve data from a shared Evernote notebook, such as this one: Initially attempted using Beautiful Soup: url = 'https://www.evernote.com/pub/missrspink/evernoteexamples#st=p&n=56b67555-158e-4d10-96e2-3b2c57ee372c' r = requests.g ...