1

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.

0

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

works perfectly - except I switched a and b in the concatenate.
@birdmw Please see here
0

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]]]

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.