Combining a 2D array with a 3D array to create a larger 3D array with an expanded third dimension

I am facing a challenge with two arrays in my coding project. Array A represents 3124 models with 5 reference parameters, while array B represents 3124 models, 19 time steps per model, and 12288 temperature field data points per time step.

My goal is to add the same 5 values from array A (parameters) to the beginning of array B for each time step, resulting in a new combined array AB = [3124, 19, 12293].

In my attempt to achieve this, I used dstack function as follows: AB = np.dstack((A, B)).shape

However, this approach resulted in an error message stating:

ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 5 and the array at index 1 has size 19

If anyone has insights or suggestions on how to overcome this issue, your help would be greatly appreciated.

Answer №1

When working with more modest shapes (my B is too large for my machine), the following adjustments can be made:

In [4]: A = np.ones((3,4)); B = 2*np.ones((3,5,133))

To make A compatible with the dimensions of B, we can do the following:

In [5]: A[:,None,:].shape
Out[5]: (3, 1, 4)
In [6]: A[:,None,:].repeat(5,1).shape
Out[6]: (3, 5, 4)

By performing these steps, the arrays will match on axis 0 and 1, except for the last one being joined:

In [7]: AB=np.concatenate((A[:,None,:].repeat(5,1),B),axis=2)
In [8]: AB.shape
Out[8]: (3, 5, 137)

These corrections address the issue mentioned in the error message:

ValueError: all the input array dimensions for the concatenation 
axis must match exactly, but along dimension 1, the array at 
index 0 has size 5 and the array at index 1 has size 19

Answer №2

If you're looking for a solution to manipulate arrays in Python, consider the following code snippet:

import numpy

array1 = numpy.asarray([3124, 5])
array2 = numpy.asarray([3124, 19, 12288])

result_array = numpy.copy(array2)

result_array[2] += array1[1]

print(list(result_array))

output: [3124, 19, 12293]

It's important to clarify your overall goal when working with arrays to ensure the most effective solution is achieved.

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

Using AJAX to send an array as a response from Laravel

After implementing Laravel to handle an AJAX post request, I encountered an issue with displaying the route data. public function infoRoute(Request $request) { // Extracting required information $ship_id = $request->ship_id; ...

A guide on mapping an array and removing the associated element

I have an array called responseData, which is used to display the available card options on the screen. public responseData = [ { id: 1399, pessoa_id: 75898, created_at: '2022-11-08T16:59:59.000000Z', holder: 'LEONARDO ', validade: ...

Disparity in outcomes from the integer division operator

Today, I made an interesting observation regarding floor division: >>> 10.1/1.01 10.0 >>> 10.1//1.01 9.0 >>> 2688937/268893.7 10.0 >>> 2688937//268893.7 9.0 >>> 6.6/3.3 2.0 >>> 6.6//3.3 2.0 I'm ...

Locate the text of an element that is not visible on the screen while the code is running

Currently, I am diving into the world of web scraping using Selenium. To get some practical experience, I decided to extract promotions from this specific site: https://i.stack.imgur.com/zKEDM.jpg This is the code I have been working on: from selenium im ...

Is there a way to delete specific characters from a tuple that I have created using Python and appJar?

After creating a tuple using an SQL statement, I'm facing an issue when trying to print it in a text box. Some items are displaying with extra symbols like {}. For example, the item {The Matrix} has these characters, while singular items such as Incep ...

Scraping a JavaScript page using Python without requiring a browser installation

Currently, I am facing a challenge in scraping an HTML element from a webpage. The content within this element is dynamically generated by Javascript, making it impossible to retrieve using a simple requests.GET: response = requests.get(url). While explor ...

`There is an issue with returning member voice state values in discord.py``

I have encountered an issue with the following code snippet. Despite having all necessary permissions for the bot, when I call it using "fetch_member", it returns None. I am unsure of how to address this problem and would appreciate any assista ...

An array containing multiple arrays in JSon format

I am currently working on creating a JSon document along with its corresponding xsd file to generate JAXB classes, and I'm not entirely sure if I am doing it correctly. The structure I aim to achieve is as follows: team -name="name" -game="game ...

Using Networkx to Assign Different Colors to Groups of Nodes in a Graph

I'm working on drawing a network where each community is represented by colored nodes (I already have node lists for each community). This is what I currently have: plot = nx.draw(G3, nodecolor='r', node_color= 'white', edge_colo ...

Ways to enhance the size of aircraft in Plotly

Upon analyzing the code snippet import pandas as pd import plotly.graph_objects as go import numpy as np df = pd.read_csv('https://raw.githubusercontent.com/tiago-peres/immersion/master/Platforms_dataset.csv') fig = px.scatter_3d(df, x='Fu ...

How can I achieve the same functionality as C# LINQ's GroupBy in Typescript?

Currently, I am working with Angular using Typescript. My situation involves having an array of objects with multiple properties which have been grouped in the server-side code and a duplicate property has been set. The challenge arises when the user updat ...

Tips for preventing a socket timeout while using the Selenium webdriver

I have been dealing with a complex Python-Selenium test suite for testing a non-public webpage. In this setup, I need to initialize the webdriver using the following code snippet: self.driver = webdriver.Firefox(firefox_profile = profile, log_path = logfi ...

Displaying Time in 24-hour format in Django Admin DateTimeField

I did some searching on Google, but I couldn't find a solution. On the Django admin side, I have the start date and end date displayed with time in 24 hr format. However, I would like to change it to display in 12 hr format instead. class CompanyEven ...

Incorporating Radar Visuals into a Customized Widget

I have been attempting to incorporate the Radar chart code (found at this link) into a GUI that includes a widget. Instead of simply plotting x and y values on the widget, my goal is to display a radar chart, but I'm facing difficulties in achieving t ...

An error in Selenium WebDriver occurs specifically with the chromedriver.exe file

While attempting to execute the command below in python/Selenium using selenium import webdriver browser=webdriver.Chrome("C:\chromedriver.exe") I encountered the following exception: selenium.common.exceptions.WebDriverException: Message: unknown ...

CrispyForms: FormHelper - Easily move the </form> tag to a different location and manage multiple forms from a single model

When utilizing FormHelper and invoking the Form using {% crispy form %}, it generates a Form wrapped within <form> tags. However, my Template is structured into two columns. The first column displays the dynamically generated {% crispy form %}. The ...

attempting to incorporate a custom dataset into TensorFlow using tfds results in errors

After following a tutorial on creating custom datasets for TensorFlow at this link, I attempted to create my own dataset using the `tfds` command. Upon entering the command `tfds new my_dataset`, I encountered the following error: tfds new my_dataset Trac ...

Retrieving Data from Vue JS Store

I am fetching value from the store import {store} from '../../store/store' Here is the Variable:- let Data = { textType: '', textData: null }; Upon using console.log(store.state.testData) We see the following result in the cons ...

Steps for incorporating a sophisticated (not in the real versus complex meaning) function

I have this complex equation representing the pressure distribution around a spherical object, with various components such as real coefficients, legendre polynomials and spherical functions. I am looking to integrate this equation over theta by defining a ...

Steps for executing a singular GETNEXT request in PySNMP

I am currently attempting to execute a basic SNMP GETNEXT query in order to retrieve the next item of a specific OID within the tree hierarchy. Essentially, what I am looking for is: When sending a GETNEXT request with the OID 1.3.6.1.2.1.1 (iso.org.dod. ...