0

I would like to take two 1D arrays

Ne_initial = Ne[:,0]
Ne_final = Ne[:,-1]

and append them to an existing 2D array as the first (Ne_initial) and last (Ne_final) rows. I am unsure how to do this. Can anyone help?

Brandon
  • 91
  • 1
  • 11

3 Answers3

0

You can use this code:

my_2d_array = []

my_2d_array.insert(0, Ne_initial)
my_2d_array.append(Ne_final)
  • That only works if the 2D array is empty, which it isnt. My question is more so how to add these two 1D arrays to the beginning and then the end of the pre-existing 2D array – Brandon Jun 15 '18 at 19:35
  • this method also does not work if objects are not lists. My objects are np.arrays, not lists. – Brandon Jun 15 '18 at 19:55
0

The following example should accomplish what you want:

IN:

import numpy as np

existing2Darray = np.matrix([[8, 3, 6, 1],[2, 5, 4, 2],[7, 2, 5, 1]])
Ne_initial = existing2Darray[:,0]
Ne_last = existing2Darray[:,-1]

OUT:

 [[8 3 6 1]
 [2 5 4 2]
 [7 2 5 1]]

[[8]
 [2]
 [7]]

[[1]
 [2]
 [1]]

IN:

np.append(existing2Darray, Ne_initial, axis=1))

OUT:

[[8 3 6 1 8]
 [2 5 4 2 2]
 [7 2 5 1 7]]

IN:

np.insert(existing2Darray, [0], Ne_last, axis=1))

OUT:

[[1 8 3 6 1]
 [2 2 5 4 2]
 [1 7 2 5 1]]
rahlf23
  • 8,869
  • 4
  • 24
  • 54
0
import numpy as np 
a = np.array([[1,2],[3,4]]) 

print 'First array:' 
print a 
print '\n'  
b = np.array([[5,6],[7,8]]) 

print 'Second array:' 
print b 
print '\n'

print 'Vertical stacking:' 
c = np.vstack((a,b)) 
print c # creating a 2-D array
col1=np.array([2,3,4,5])
col2=np.array([1,1,1,1])
d=np.column_stack((a1,b2))
np.concatenate((d,c)) # adding back to existing array
mad_
  • 8,121
  • 2
  • 25
  • 40
  • I had to tweak your answer a bit for it to work: instead of np.vstack I had to use np.hstack, and for it to work properly I had to reshape the initial and final 1D arrays so that their shapes were (#,1) instead of (#,). with those edits, this works! – Brandon Jun 15 '18 at 20:59