Han Zhengzu
Han Zhengzu

Reputation: 3852

combine 2-d array to existing 3-d array

>>>d1.shape
>>>(18,18)
>>>d2.shape
>>>(18,18)
>>>d3 = array([d1, d2])
>>>d3.shape
>>>(2, 18, 18)  

If I have already got the d3 with shape(2,18,18) and I want to add another 2-d array d4 (18x18) into d3 to make 3-d array(3,18,18).
What should I do?

====2015-12-31=====

Summary

From the answer below, I collect some useful code here

  1. d3 = np.concatenate([d3, d4.reshape(1, d3.shape[0],d4.shape[1])])

  2. d3 = np.vstack([d3, d4[None, ...]])

PS

After my test for construct 3-d array(681x50x60) by reading 681 .csv file,
the second method was more efficient(19 s) than the first method(28 s) on the same laptop.

Upvotes: 4

Views: 232

Answers (2)

Zachi Shtain
Zachi Shtain

Reputation: 836

Same as you did with d3 only you have to reshape d4 into a 3-d array:

d3 = array([d3, d4.reshape(1, 18, 18)])

or

d3 = concatenate([d3, d4.reshape(1, 18, 18)])

Upvotes: 5

ilent2
ilent2

Reputation: 5241

The following might be useful, but I imagine there is a more efficient way to achieve the same result...

import numpy as np
d1 = np.array([[1, 2, 3], [4, 5, 6]])
d2 = np.array([[7, 8, 9], [1, 2, 3]])
d3 = np.array([d1, d2])

dnew = np.array([[6, 5, 4], [3, 2, 1]])
d3 = np.array([dnew] + [d3[a, ...] for a in range(d3.shape[0])])

# Add to the end of the array
dlast = np.array([[6, 5, 4], [3, 2, 1]])
d3 = np.array([d3[a, ...] for a in range(d3.shape[0])] + [dlast])

Edit: There is a better way

In this question the stack command is used to literally stack the arrays together. As an example consider:

import numpy as np
d1 = np.array([[1, 2, 3], [4, 5, 6]])
d2 = np.array([[7, 8, 9], [1, 2, 3]])
d3 = np.array([d1, d2])

dnew = np.array([[6, 5, 4], [3, 2, 1]])
d3 = np.vstack([d3, dnew[None, ...]])

There is an important difference between using np.vstack and just creating a new array using np.array. The latter (tested on numpy version 1.8.2) produces an array of two objects while stack produces a single numpy array.

Upvotes: 1

Related Questions