2

I have some problem about 3D python numpy

import numpy as np
n = 5
m = 4

Sc = np.random.rand(m,n,n)
S1 = np.zeros((1,n+2))
S2 = np.zeros((n,1))

A0 = np.r_[S1, np.c_[S2, Sc[0], S2], S1]
A1 = np.r_[S1, np.c_[S2, Sc[1], S2], S1]
#print(A)
#print(B)
A = np.array([A0,A1])
A.shape
Atmp = np.r_[S1, np.c_[S2, Sc[2], S2], S1]

Dimension of A = (2, 7, 7)

and dimension of Atmp = (7,7).

How to append Atmp to A ?

4
  • 2
    Atmp + A doesn't give any errors for me. Maybe A += Atmp? You need to clarify exactly what you want. Commented Aug 7, 2017 at 8:22
  • no, I mean to apend Atmp to array A Commented Aug 7, 2017 at 8:24
  • 1
    A = np.array((A0, A1, Atmp)) or A = np.vstack((A, Atmp[None,...])) Commented Aug 7, 2017 at 9:05
  • 1
    np.append is another way of usingnp.concatenate, and often a confusing one. np.r_ and np.c_ are also concatenate frontends. Commented Aug 7, 2017 at 9:07

3 Answers 3

4

Don't concatenate/append/stack arrays if you can help it, especially big ones. It's very wasteful of memory and slow.

Assign A = np.empty((m, n+2, n+2)) and then fill it with A[i] = np.r_[S1, np.c_[S2, Sc[i], S2], S1]. Or do it vectorized and get rid of the for loops:

A = np.zeros((m, n+2, n+2))
A[:,1:-1,1:-1] = Sc

or even do it in one line:

A = np.pad(Sc, ((0,0),(1,1),(1,1)), 'constant', constant_values = 0)
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your answer, It's very helpful for my problem. And this is a big dimension array problem, can you suggest some reading for this method?
I think this answer not only give me the answer of the problem but also new way to use big problem array in python. Thakn you very much and I vote this for the acceptance answer
2

You can try this:

A = np.concatenate([A, [Atmp]])

1 Comment

Thank you for your answer, I think, this answer work for my problem.
1

You can use reshape to put the array in the right form:

np.reshape(Atmp,(1, Atmp.shape[0], Atmp.shape[1]))

and then append as

np.vstack([A, np.reshape(Atmp,(1, 7, 7))])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.