Home > Enterprise >  How to check if all the values in a row/column of a Numpy array are equal to some specific value? At
How to check if all the values in a row/column of a Numpy array are equal to some specific value? At

Time:10-10

I am programming TicTacToe game using Numpy and Pandas dataframe, however, the function which checks if all the values in a column are equal to 'X', does not seem to work, because of the error below. Does anyone know how to check if all the values in a column are equal to X, or better check the columns, rows, and diagonals in one function?

File "c:...", line 46, in win1 if ('X' == a).all(): return ('X' == a).all() AttributeError: 'bool' object has no attribute 'all'

def win1(board):
    for i in column_names:
        a = np.array(board[i])
        if ('X' == a).all(): return ('X' == a).all()
board = np.array([ [0, 0, 0], 
                   [0, 0, 0], 
                   [0, 0, 0], ])

column_names = ['a', 'b', 'c']
row_names    = ['1', '2', '3']
board = pd.DataFrame(board, columns=column_names, index=row_names)

Thank you for help in advance.

CodePudding user response:

I would first try to understand why the error comes up by including:

y=(a=="X")
print(y)

CodePudding user response:

This should hopefully get you going: It will calculate if all values in the column are equal to X

import pandas as pd

def win1(board):
    for col in board.columns:
        if (board[col] == 'X').all():
            print(f"Column {col} : All values equal to X")
        else:
            print(f"Column {col} : Some values NOT equal to X")

board = np.array([ [0, 'X', 0], 
                   [0, 'X', 'X'], 
                   [0, 'X', 0], ])

column_names = ['a', 'b', 'c']
row_names    = ['1', '2', '3']
board = pd.DataFrame(board, columns=column_names, index=row_names)

# Check each column for a win
win1(board)

OUTPUT:

Column a : Some values NOT equal to X
Column b : All values equal to X
Column c : Some values NOT equal to X
  • Related