birdmw
birdmw

Reputation: 875

Cloning a column in 3d numpy array

Let's say I have a 3D array representing tic-tac-toe games (and their respective historical states):

[ 
  [[0,0,0,1,1,0,0,0,1]], #<<--game 1
  [[1,0,0,1,0,0,1,0,1]], #<<--game 2
  [[1,0,0,1,0,0,1,0,1]]  #<<--game 3
]

I would like to pre-pend a clone of these states, but then keep the historical records growing out to the right where they will act as an unadultered historical record

So the next iteration would look like this:

[ 
  [[0,0,0,1,1,0,0,0,1], [0,0,0,1,1,0,0,0,1]], #<<--game 1
  [[1,0,0,1,0,0,1,0,1], [1,0,0,1,0,0,1,0,1]], #<<--game 2
  [[1,0,0,1,0,0,1,0,1], [1,0,0,1,0,0,1,0,1]]  #<<--game 3
]

I will then edit these new columns. At a later time, I will copy it again.

So, I always want to copy this leftmost column (pass by value) - but I don't know how to perform this operation.

Upvotes: 1

Views: 126

Answers (2)

Ruzihm
Ruzihm

Reputation: 20249

You can do this using hstack and slicing:

import numpy as np
start= np.asarray([[[0,0,0,1,1,0,0,0,1]],[[1,0,0,1,0,0,1,0,1]],[[1,0,0,1,0,0,1,0,1]]])
print(start)

print("duplicating...")
finish = np.hstack((start,start[:,:1,:]))

print(finish)

print("modifying...")
finish[0,1,2]=2

print(finish)
[[[0 0 0 1 1 0 0 0 1]]

 [[1 0 0 1 0 0 1 0 1]]

 [[1 0 0 1 0 0 1 0 1]]]
duplicating...
[[[0 0 0 1 1 0 0 0 1]
  [0 0 0 1 1 0 0 0 1]]

 [[1 0 0 1 0 0 1 0 1]
  [1 0 0 1 0 0 1 0 1]]

 [[1 0 0 1 0 0 1 0 1]
  [1 0 0 1 0 0 1 0 1]]]
modifying...
[[[0 0 0 1 1 0 0 0 1]
  [0 0 2 1 1 0 0 0 1]]

 [[1 0 0 1 0 0 1 0 1]
  [1 0 0 1 0 0 1 0 1]]

 [[1 0 0 1 0 0 1 0 1]
  [1 0 0 1 0 0 1 0 1]]]

Upvotes: 0

Poe Dator
Poe Dator

Reputation: 4893

You can use concatenate:

# initial array
a = np.array([ 
  [[0,0,0,1,1,0,0,0,1], [0,1,0,1,1,0,0,0,1]], #<<--game 1
  [[1,0,0,1,0,0,1,0,1], [1,1,0,1,0,0,1,0,1]], #<<--game 2
  [[1,0,0,1,0,0,1,0,1], [1,1,0,1,0,0,1,0,1]]  #<<--game 3
])

#subset of this array (column 0)
b = a[:,0,:]

# reshape to add dimension 
b = b.reshape ([-1,1,9])

print(a.shape, b.shape)  # ((3, 2, 9), (3, 1, 9))

# concatenate:
c = np.concatenate ((a,b), axis = 1)

print (c)

array([[[0, 0, 0, 1, 1, 0, 0, 0, 1],
        [0, 1, 0, 1, 1, 0, 0, 0, 1],
        [0, 0, 0, 1, 1, 0, 0, 0, 1]], # leftmost column copied

       [[1, 0, 0, 1, 0, 0, 1, 0, 1],
        [1, 1, 0, 1, 0, 0, 1, 0, 1],
        [1, 0, 0, 1, 0, 0, 1, 0, 1]], # leftmost column copied

       [[1, 0, 0, 1, 0, 0, 1, 0, 1],
        [1, 1, 0, 1, 0, 0, 1, 0, 1],
        [1, 0, 0, 1, 0, 0, 1, 0, 1]]]) # leftmost column copied

Upvotes: 1

Related Questions