简体   繁体   中英

How do i add an np.array to an existing np.array without merging the two?

I'm making a minimax algorithm in Python that plays tic tac toe. I need to store all possible combinations of ndarrays in a different ndarray. I'm storing the board in a numpy array, so an empty board would be [[0,0,0],[0,0,0],[0,0,0]] , an X is a 1 and an O is a -1. I wanted to do it in this way: first off, I have an np.array([]) to which I add all states possible to happen after the next move, so for the first move on the board it would look something like [[[1,0,0],[0,0,0],[0,0,0]],[[0,1,0],[0,0,0],[0,0,0]],[...]] . I tried np.append and np.concatenate, but I can't get it to work as I'd like. How should I go about it?

The only trick you need is Broadcasting to generate an aditional dimention to stack. (here i've created the first state condition with this aditional dimension but you could broadcast it before stackin

Here a posible solution:

import numpy as np


states = np.random.randn(1,3,3)
print(f"actual Shape is: {states.shape}")

for i in range(3):
    newState = np.random.randn(3,3)
    states = np.append(states,newState[None,:,:],axis=0)
    print(f"actual Shape is: {states.shape}")

Also you could use vstack or concatenate

states = np.vstack([states,newState[None,:,:]])

states = np.concatenate([states,newState[None,:,:]],axis=0)

This can be done withnp.append . When appending numpy arrays, the arrays should have the same number of dimensions. Hence, in order to get the outcome you want you can proceed like so:

import numpy as np

tictactoe = np.zeros(shape=(1, 3, 3)) # create an empty array
n = np.array([[[0, 0, 0], [0, 1, 0], [0, 1, 0]]]) # example of value to add

tictactoe = np.append(tictactoe, n, axis=0) # adding the value in
print(tictactoe)

in order to make the np.append work, notice that I am passing one of the boards into the first axis axis=0 as a three dimensional array [[[0, 0, 0], [0, 1, 0], [0, 1, 0]]] . Notice the triple brackets. This should give you an outcome of shape (2, 3, 3) where the 2 represents the number of boards you have.

Otherwise here is a basic way of doing it without numpy by simply appending a list:

tictactoe = []
n = [[0, 0, 0], [0, 1, 0], [0, 1, 0]]
tictactoe.append(n)
print(tictactoe)

Nb As @hpaulj noted within the comments, np.append with axis is the same as np.concatenate . Such iterative uses can be quite slow, and require special care when starting. Here is a link to a related issue .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM