def __init__(self): pygame.init() self.manager = GameManager() self.enemy = Ai() pygame.display.set_caption("Tic Tac Toe") self.WIDTH = 540 self.HEIGHT = 540 self.screen = pygame.display.set_mode((self.WIDTH, self.HEIGHT)) self.background = pygame.Surface((self.WIDTH, self.HEIGHT)) self.background.fill(pygame.Color('#E3E3E3')) # FONTS self.playerFont = pygame.font.SysFont('arial', 70) self.resultFont = pygame.font.SysFont('arial', 60, bold=True) self.infoFont = pygame.font.SysFont('arial', 30, italic=True) # define cell dimensions self.cellWidth = self.WIDTH / 3 self.cellHeight = self.HEIGHT / 3 self.board = [] # to create the 3x3 grid for i in range(3): for j in range(3): self.board.append( Cell(self.cellWidth * i, self.cellHeight * j, self.cellWidth, self.cellHeight)) self.manager.gameState = 'progress' self.running = True
def click(self, button): """Print symbol in button. Create Ai object, leads the gameplay of player and ai, check wrong moves and draw.""" intel = Ai() if button['text'] == ' ' and Button.clickable: if Game.computer_move_quantity < 4: button['text'] = 'X' Game.player_move_quantity += 1 Button.clickable = False gameboardcls.Gameboard.gameboard_obj.check_global_win('X') if not Button.clickable: if Game.player_move_quantity <= 4: intel.move_to_win() Game.computer_move_quantity += 1 Button.clickable = True gameboardcls.Gameboard.gameboard_obj.check_global_win( 'O') else: messagebox.showinfo( 'Attention', 'It seems to be a draft\n Lets restart game') self.new_game_button_func() else: messagebox.showinfo( 'Attention', 'It seems to be a draft\n Lets restart game') self.new_game_button_func() else: messagebox.showerror( 'Attention', 'Oops... This button has already been pushed\n Choose another one' )
def test_random(self): board = Board(tk.Toplevel()) ai = Ai('black', board.squares, board, None, None) ai.random() piece = board.squares[(ai.rowpiece, ai.colpiece)]['piece'] if piece is not None: self.assertTrue(piece.color == 'black')
def __init__(self): self._board = Board() self._other_board = Board() self._game = Game(self._board) self.control_game = Game(self._other_board) # Takes the exact board as the displayed game self._ai = Ai(self.control_game)
def start(): g = Game() try: choice2 = (int(input("Write 1 to reload or 0 to have a new game:"))) if choice2 == 1: g.service.read_file() elif choice2 != 0: print("Wrong number!") except Exception as e: print(e) print(g) ai = Ai(g.board, g.service) while True: try: g.input() if g.service.Order_won() == True: raise ex.HumanWon("Order has Won!!!") ai.random_move() if g.service.Order_won() == True: raise ex.HumanWon("Order has Won!!!") print(g) ai.free_moves() except ex.HumanWon as e: print(e) break except Exception as e: print(e)
def get_move(): fen_str = request.args.get('fen') print(fen_str) if fen_str is None: return "Provide fen" ai = Ai() value, move = ai.get_move(fen_str=fen_str) return move
def index(): rawData = request.get_json() if rawData: fetch = [block for block in rawData['boardInfo']['blocks']] blocks = sorted(fetch, key=lambda k: k['x']) ai = Ai(blocks, rawData['side']) #logging.debug('EXPECT:' + str(ai.expect_score)) move = ai.get_move_score() #logging.debug('MOVE:' + str(move)) keep = ai.get_keep_score() #logging.debug('KEEP:' + str(keep)) flip = ai.get_flip_score() #logging.debug('FLIP:' + str(flip)) collector = {'move': move, 'keep': keep, 'flip': flip} scores = { 'move': move['score'], 'keep': keep['score'], 'flip': flip['score'] } action = max(scores, key=scores.get) if action == 'keep': scores.pop('keep') action = max(scores, key=scores.get) result = collector[action] logging.error( str({ 'EXPECT': ai.expect_score, 'MOVE': move, 'KEEP': keep, 'FLIP': flip, 'RESULT': result, 'DETAIL': { 'move': move['detail'], 'keep': keep['detail'], 'flip': flip['detail'] } })) if result['action'] == 'move': return jsonify({ 'pid': result['from']['id'], 'type': 'move', 'x': result['block']['x'], 'y': result['block']['y'] }) elif result['action'] == 'flip': return jsonify({ 'pid': result['block']['id'], 'type': 'flip', 'x': None, 'y': None }) else: # TODO return jsonify({'pid': None, 'type': 'keep', 'x': None, 'y': None})
def __init__(self, rows=None, cols=None): self.rows = rows or 6 self.cols = cols or 7 self.board = Board(self.rows, self.cols) player = input("Player 1 human or cpu?(h/c)") if player == 'h': self.players.append(Player("O")) else: self.players.append(Ai("O", 4)) player = input("Player 2 human or cpu?(h/c)") if player == 'h': self.players.append(Player("X")) else: self.players.append(Ai("X", 4)) self.currentTurn = self.players[0]
def init_players(self): self.bot = Ai(self.choices[randint(0,1)]); self.player = "X" if self.bot.choice == "O" else "O" if randint(0,1) == 1: self.bot.make_move(self.board, self.winning_combos) greeting = "Hello Player! Bot plays first! You are playing with \"" + self.player + "\"" else: greeting = "Hello Player! You are playing with \"" + self.player + "\"" self.popup_message(greeting)
def __init__(self, root): self.__root = root self.__board = Board(root) self.__bag = Bag() self.__human = Human(root) self.__ai = Ai(root, self.__board, self.__bag) self.__turn = 1 self.__player = self.__human self.__human_score = StringVar() self.__ai_score = StringVar()
def initGame(): global MINE_LEFT mines = initMines() numbers = initNumbers(mines) marked = initMarked() revealed = initRevealed() ai = Ai(mines, revealed, marked, numbers, TILE_H_NUMBER, TILE_V_NUMBER, MINE_COUNT) MINE_LEFT = MINE_COUNT return mines, numbers, revealed, marked, ai
def predict(): # Getting the data transmitted in a JSON by the POST request parameters = request.get_json(force=True) # Creating the AI ai = Ai() # Checking if the POST request was made from Postman if str(parameters['image'])[0] == '/': predicted_value: int = ai.predict(parameters['image'], True) else: # Collecting image from JSON picture_request = str(parameters['image']) starter = picture_request.find(',') image_data = picture_request[starter + 1:] image_data = bytes(image_data, encoding="ascii") # The image has been transferred encoded in base64 model, the line just below decode it and create an image form it with open('./assets/image.jpeg', 'wb') as fh: fh.write(base64.decodebytes(image_data)) # Launching the prediction predicted_value: int = ai.predict("./assets/image.jpeg", True) # Creating the data for the JSON file to be returned data_set = { "image": { "name": parameters['image'], "reshaped size": "28*28", "color scale": "grey scale" }, "Multi-Layers Perceptron spec": { "hidden_layer_sizes": "(200,)", "activation": "logistic", "alpha": "1e-4", "solver": "sgd", "tol": "1e-4", "random_state": 2, "max_iter": 200, "learning_rate_init": .0001, "verbose": "True" }, "ML algorithm score on NMIST digits": { "time": "0:05:53", "accuracy score on training data": "0.960970871012443" }, "Predicted value": predicted_value } # Creating the JSON json_to_be_returned = json.dumps(data_set) # Returning the JSON return json_to_be_returned
def define_contestants(self): # prompts user to pick a human or ai opponent self.opening_statement() opponent = input("\nPress 1 to play against a Human or type anything else to play against an AI" "\n >") if opponent == '1': self.player_one = Human() self.player_two = Human() else: self.player_one = Human() self.player_two = Ai()
def test_can_not_place_in_a_full_collum(): class Moves(): def __init__(self): self.legal_moves = [ "Full", [1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0] ] move_array = [0, 1] def mock_move(): return move_array.pop(0) computer = Ai(Moves()) computer.select_move = mock_move i = 0 assert computer.move() == 1
def main(): pb = PiecesBank() app = UI() ### DO NOT F*****G REMOVE THIS. I DARE YOU. ### app.preloadPieces(pb.pieceslist) ai = Ai() arbiter = Arbiter() board = Board() app.setBatchMethod(lambda loop, fitness, mutation: ai.main_function( pb, app, arbiter, board, loop, fitness, mutation)) # app.drawTable(board) app.drawTable(generatedSolvedPuzzle(pb)) ### DO NOT F*****G REMOVE THIS EITHER. ### app.mainloop()
def MainMenu(self): userInput = input( "Press 1 for Human vs AI, Press 2 for Human vs Human") if userInput != '1' and userInput != '2': self.MainMenu() if userInput == "1": self.p1 = Human("P1") self.p2 = Ai("P2", random) #console clear self.PlayGame() else: self.p1 = Human("P1") self.p2 = Human("P2") #console clear self.PlayGame()
def __init__(self, players, board_length, board_height, goal, gravity, depth, win): self.players = players self.board_length = board_length self.board_height = board_height self.goal = goal self.gravity = gravity self.win = win self.win_size = win.get_size() self.tile_length = int(self.win_size[0] * 0.9 / board_length) self.tile_height = int(self.win_size[1] * 0.9 / board_height) self.length_offset = int(self.win_size[0] * 0.05) self.height_offset = int(self.win_size[1] * 0.05) self.game_board = self.get_game_board() self.event = None self.turn = 0 self.winner = None self.ai = Ai(self.game_board, gravity, goal, players, depth)
def run(): pygame.init() screen = pygame.display.set_mode(Settings.resolution) pygame.display.set_caption('Snake') generate_all_positions(screen) wall = Wall(screen) snake = Snake(screen) food = Food(screen, snake) ai = Ai(screen, snake, food) Settings.ai = ai Settings.ai.get_shortest_path(food.rect.x, food.rect.y) Settings.ai.set_new_path() while True: check_events(screen, snake) update(screen, snake, food, ai, wall) time.sleep(0.01)
def create_player(self): """P1 is blue, P2 is Yellow, P3 is Red, P4 is Green, P5 is Purple.""" color_idx = len(constants.COLORS) - 1 for i in range(self.humans): x, y = self.get_random_coord() self.players.append( Player("P" + str(i + 1), x, y, constants.COLORS[color_idx])) color_idx -= 1 for i in range(self.bots): x, y = self.get_random_coord() self.players.append( Ai( "COM" + str(i + 1), x, y, constants.COLORS[color_idx], self.difficulty, )) color_idx -= 1
def __init__(self,tablero,jugador1,jugador2,con_jugadas_posibles=True,nivel=Ai.FACIL, write_path=""): #self.__gui = Gui() #self.__tablero = self.__gui.init_board().get_board() self.__tablero_g = tablero self.__tablero = tablero.get_logical_board() #Iniciliazo la inteligencia para la PC self.__pc = Ai(nivel) #Inicializo un vector de jugadores self.__jugadores = [jugador1,jugador2] self.__ganador = "" self.__nro_turno = 0 self.__termino_juego = False self.__juego_mesh = False self.__con_jugadas_posibles = con_jugadas_posibles self.__lista_jugadas_posibles = [] if write_path != "": #Imprimo en el log la configuracion del juego que se inicia try: f = open(os.path.abspath(write_path + "/data/game.log"),'r') f.close() self.__log_file = open(os.path.abspath(write_path + "/data/game.log"),'a') print >> self.__log_file, '\nGAME LOG: ' + time.asctime() except: self.__log_file = open(os.path.abspath(write_path + "/data/game.log"),'w') print >> self.__log_file, 'GAME LOG: ' + time.asctime() print >> self.__log_file, 'Tablero: ' + str(self.__tablero.get_dimension()) + 'x' + str(self.__tablero.get_dimension()) if jugador1.get_color() == board.BLANCO and jugador1.get_name() == PC: print >> self.__log_file, 'PC: Blanco' print >> self.__log_file, 'Jugador: Negro' elif jugador1.get_name() == HUMANO and jugador2.get_name() == HUMANO: if jugador1.get_color() == board.BLANCO: print >> self.__log_file, 'Jugador1: Blanco' print >> self.__log_file, 'Jugador2: Negro' else: print >> self.__log_file, 'Jugador1: Negro' print >> self.__log_file, 'Jugador2: Blanco' else: print >> self.__log_file, 'PC: Negro' print >> self.__log_file, 'Jugador: Blanco'
def __init__(self, root, parent, port, ip=None): self.game_obj = Game() self._ai_mode = False print('parent:', parent) print('port:', port) """ Initializes the GUI and connects the communicator. :param parent: the tkinter root. :param ip: the ip to connect to. :param port: the port to connect to. :param server: true if the communicator is a server, otherwise false. """ self._root = root self._parent = parent self.__communicator = Communicator(root, port, ip) self.__communicator.connect() self.__communicator.bind_action_to_message(self.__handle_message) self.__place_widgets() #self.frame = t.Frame(self._parent, width=800, height=800) self._canvas = t.Canvas(root, width=700, height=600, bg='blue') self._grid = t.Grid() #self.frame.pack() self._canvas.pack() self._create_circle() if parent == 'ai': self.ai_obj = Ai() self._ai_mode = True if (server == True and self.game_obj.get_current_player() == 0) or (server == False and self.game_obj.get_current_player() == 1): self.ai_move() else: self._canvas.bind("<Button-1>", self.callback)
def post(self): print("Test") i = "input.jpg" lan = "hi" text, interface_lang, label_, arr_all = Core(i, lan) find, aware, type_, certain_tag, awarness = Ai(interface_lang, label_) img = cv.imread('p3/' + i) for i in arr_all: pts = np.array(i, np.int32) pts = pts.reshape((-1, 1, 2)) cv.polylines(img, [pts], True, (0, 0, 255), 5) cv.imwrite('static/test_img.jpg', img) assign_cluster = 0 analysis = { "regional_language": str(text), "translated_text": str(interface_lang), "cluster": assign_cluster, "tags": label_, "type": type_ } print(analysis) return jsonify(analysis)
def loop(self, screen): screen.blit(self.text, self.textRect) screen.blit(self.text2, self.textRect2) clock = pygame.time.Clock() self.snake = Snake(self.display, -(Config['snake']['width'])) self.snake2 = Snake(self.display, (Config['snake']['width'])) apple = Apple(self.display) ai = Ai() x_change = Config['snake']['speed'] y_change = 0 x_change2 = -Config['snake']['speed'] y_change2 = 0 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT and x_change == 0: x_change = -Config['snake']['speed'] y_change = 0 elif event.key == pygame.K_RIGHT and x_change == 0: x_change = Config['snake']['speed'] y_change = 0 elif event.key == pygame.K_UP and y_change == 0: x_change = 0 y_change = -Config['snake']['speed'] elif event.key == pygame.K_DOWN and y_change == 0: x_change = 0 y_change = Config['snake']['speed'] if event.key == pygame.K_a and x_change2 == 0: x_change2 = -Config['snake']['speed'] y_change2 = 0 elif event.key == pygame.K_d and x_change2 == 0: x_change2 = Config['snake']['speed'] y_change2 = 0 elif event.key == pygame.K_w and y_change2 == 0: x_change2 = 0 y_change2 = -Config['snake']['speed'] elif event.key == pygame.K_s and y_change2 == 0: x_change2 = 0 y_change2 = Config['snake']['speed'] snake_rect = self.snake.draw(Config['colors']['blue']) snake_rect2 = self.snake2.draw(Config['colors']['green']) apple_rect = apple.draw() ai.update(pos=(snake_rect[0], snake_rect[1]), apple=(apple_rect[0], apple_rect[1]), size=self.snake.max_size) move = ai.action() bumper_x = Config['game']['width'] - Config['game']['bumper_size'] bumper_y = Config['game']['height'] - Config['game']['bumper_size'] if apple_rect.colliderect(snake_rect): apple.remove() apple.randomize() self.snake.eat() elif apple_rect.colliderect(snake_rect2): apple.remove() apple.randomize() self.snake2.eat() snakehit = self.snake.hit(self.snake2.body, bumper_x, bumper_y) snakehit2 = self.snake2.hit(self.snake.body, bumper_x, bumper_y) if (snakehit or snakehit2): if (snakehit and snakehit2): print("Tie") elif snakehit: self.snake2.score += 1 self.player2score += 1 else: self.snake.score += 1 self.player1score += 1 apple.remove() # snake.remove() self.map(screen) self.loop(screen) self.snake.move(x_change, y_change) self.snake2.move(x_change2, y_change2) pygame.display.update() clock.tick(Config['game']['fps'])
def main(self): logging.basicConfig(filename='log_uci.log', level=logging.DEBUG) def output(line): print(line, flush=True) logging.debug(line) engine_quit = False while True: engine_input = input() logging.debug(f'>>> {engine_input} ') # Quit engine if engine_input in 'quit stop': break # Engine info elif engine_input == 'uci': output('id name Endamat Chess') output('id author Elias Nilsson') output('uciok') # Check to see if engine is ready elif engine_input == 'isready': output('readyok') # Create a new game elif engine_input == 'ucinewgame': self.gamestate = GameState('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1') # Handle a given position elif engine_input.startswith('position'): # Split engine input into parts inputs = engine_input.split() try: # Handle building up the board from a FEN string if inputs[1] == "fen": # If moves are given in input, initiate board and make the moves if "moves" in inputs: # Find the entire FEN in the command fen = ' '.join(inputs[2:inputs.index('moves')]) self.gamestate = GameState(fen) # Loop through the moves and make them on the board moves = inputs[inputs.index('moves') + 1:] for move in moves: gamestate_move = self.parse_move(move) self.gamestate.make_move(gamestate_move) else: fen = ' '.join(inputs[2:]) self.gamestate = GameState(fen) # Handle board from building up the board from the start pos elif inputs[1] == "startpos": # Init board state to start pos self.gamestate = GameState('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1') # If moves are given in input, initiate board and make the moves if 'moves' in inputs: # Loop through the moves and make them on the board moves = inputs[inputs.index('moves') + 1:] for move in moves: gamestate_move = self.parse_move(move) self.gamestate.make_move(gamestate_move) else: print("Unknown position type") except Exception as exep: print("Something went wrong with the position. Please try again") print(exep) # The go command will initiate search and we need to output best move from given position elif engine_input.startswith('go'): # Default options depth = -1 time = -1 movetime = -1 stoptime = 0 inc = 0 timeset = 0 movestogo = 50 # Loop through given parameters after go command _, *params = engine_input.split(' ') for param, value in zip(*2*(iter(params),)): # Infinite search if param == 'infinite': pass # Fixed depth search elif param == 'depth': depth = max(1, int(value)) # Can't use 0 or negative values as depth # Black time increment if black turn elif param == 'binc': if not self.gamestate.is_white_turn: inc = int(value)/1000 # White time increment if white turn elif param == 'winc': if self.gamestate.is_white_turn: inc = int(value)/1000 # Black time limit elif param == 'btime': if not self.gamestate.is_white_turn: time = int(value)/1000 # White time limit elif param == 'wtime': if self.gamestate.is_white_turn: time = int(value)/1000 # Amount of time allowed to make a move elif param == 'movetime': movetime = int(value)/1000 # Number of moves to go before time gets increased elif param == 'movestogo': movestogo = int(value) # Different time controls placeholder else: print(f'"{param}" with value "{value}" is not a valid/legal input command.') # If depth is not available, set it to something large if depth == -1: depth = 64 # Init start time starttime = t.time() # If move time was given, update time to movetime and moves to go to 1 (1 move in x ms) if movetime != -1: time = movetime movestogo = 1 # If time control is available, flag that we play with time control and set timing if time != -1: timeset = 1 # Divide time equally between how many moves we should do time /= movestogo # Lag compensation 100 ms if time > 1.5: time -= 0.1 # Add time and increment to get what time we should stop at stoptime = starttime + time + inc # Increment when time is almost up if time < 1.5 and inc and depth == 64: stoptime = starttime + inc - 0.1 # Search position given the parameters from GUI searcher = Ai(self.gamestate, search_depth=depth, stoptime=stoptime, timeset=timeset) searcher.nodes = -1 searcher.time_start = t.time() # Initialize best move and best score self.best_move = self.gamestate.get_valid_moves()[0] self.best_score = 0 for current_depth in range(1, depth + 1): # Break if time is up if searcher.stopped or engine_quit: break # Calculate move and score for current depth move, score = searcher.ai_make_move(current_depth=current_depth, best_move=self.best_move, best_score=self.best_score) # Print info to GUI after each depth if we returned a valid move (engine didn't stop calculating). # Check if we reached mate score, if so calculate how many moves left until mate to print in GUI. if not searcher.stopped: if -searcher.mate_value < score < -searcher.mate_score: output('info score mate %d depth %d nodes %ld time %d pv %s' % (-(score + searcher.mate_value) / 2 - 1, current_depth, searcher.nodes, searcher.timer * 1000, searcher.pv_line)) elif searcher.mate_score < score < searcher.mate_value: output('info score mate %d depth %d nodes %ld time %d pv %s' % ((searcher.mate_value - score) / 2 + 1, current_depth, searcher.nodes, searcher.timer * 1000, searcher.pv_line)) else: output('info score cp %d depth %d nodes %ld time %d pv %s' % (score, current_depth, searcher.nodes, searcher.timer * 1000, searcher.pv_line)) # Update best move and best score self.best_move, self.best_score = move, score # Output best move to engine console if self.best_move[2] in 'pQpRpBpN': output(f'bestmove {f"{s.square_to_board[self.best_move[0]]}{s.square_to_board[self.best_move[1]]}{self.best_move[2][-1].lower()}"}') else: output(f'bestmove {f"{s.square_to_board[self.best_move[0]]}{s.square_to_board[self.best_move[1]]}"}') elif engine_input.startswith('time'): our_time = int(engine_input.split()[1]) elif engine_input.startswith('otim'): opp_time = int(engine_input.split()[1]) else: output(f'"{engine_input}" is currently not a valid input command.') pass
map.draw(score_activate=(car.last_score + 1) % 8) car.draw() label.text = str(car.score) label.draw() global glob_frame glob_frame += 1 label2.text = str(glob_frame) label2.draw() if not car.player_play: f = car.rays(ai, net, map.in_map, map.out_map, True) keys.ai_keys(f) # print f fps_display.draw() if __name__ == "__main__": fps_display = FPSDisplay(window) map = CarMap() ai = Ai() net = Net() device = torch.device('cpu') net.load_state_dict( torch.load('models/' + car_model + '.txt', map_location=device)) net.double() car = Car() keys = Keyboard_helper() collision = Collision() pyglet.clock.schedule_interval(update_frames, 1 / 24.0) pyglet.app.run()
def test_Can_make_a_move(): computer = Ai(Moves()) number = computer.move() assert number >= 0 and number <= 6
def __init__(self, arg): self.opt = arg self.connect = Connect(arg) self.bot = Ai() self.last_cmd = None
def init_players(self): rand_choice = randint(0, 1) self.bot = Ai(self.choices[rand_choice], abs(rand_choice - 1)) self.player = self.choices[0] if rand_choice == 1 else self.choices[1]
import pygame import sys from board import Board from view import View from ai import Ai, Evaluators from stone_color import StoneColor board = Board() view = View() white_ai = Ai(StoneColor.WHITE, Evaluators.freedoms_evaluate) black_ai = Ai(StoneColor.BLACK, Evaluators.simple_evaluate) while True: board.make_move(black_ai.get_best_move(board, 1)) board.make_move(white_ai.get_best_move(board, 2)) game_board = board.get_board() view.draw_board(game_board)
def Cluster(dataset_name , n_classes): # n_classes = 2 X = pd.read_csv('dataset.csv',sep=',') X = X.dropna(axis = 0).reset_index() name = X[['image']] arr = X['image'].as_matrix() type_csv = [] tags_csv = [] extracted_tag = [] translated_tag = [] for i in arr: (text, extracted_lang, label_) = Core(i, lan) (find , aware , type_ , certain_tag , awarness) = Ai(extracted_lang , label_) type_csv.append(type_) tags_csv.append(str(label_)) extracted_tag.append(text) translated_tag.append(extracted_lang) X = X[['latitude','longitude']] clusterer = KMeans(n_clusters= n_classes, random_state=1 , max_iter = 10000) cluster_labels = clusterer.fit_predict(X) df = pd.DataFrame(data = X ) df2 = pd.DataFrame(data = cluster_labels , columns = ['cluster']) df3 = pd.DataFrame(data = type_csv , columns = ['type']) df4 = pd.DataFrame(data = tags_csv , columns = ['tags']) df5 = pd.DataFrame(data = extracted_tag , columns = ['Regional Lang']) df6 = pd.DataFrame(data = translated_tag , columns = ['Translated Lang']) result = pd.concat([ name , df , df2 , df3 , df4 , df5 , df6 ] , axis = 1) result.to_csv('{}_labels.csv'.format(n_classes)) arr = [] for i in range(n_classes): count = Cluster_analysis(i) DI = equation(count) print(DI) df = pd.read_csv('{}_labels.csv'.format(n_classes) , sep = ",") X = df[df['cluster'] == i] l = len(X) arr.append([round(DI,3)]*l) arr_new = np.concatenate((arr[0],arr[1]), axis=0) df_new = df.sort_values('cluster',ascending=True).reset_index() df2 = pd.DataFrame(data = arr_new , columns = ['Dev_Index']) result = pd.concat([df_new , df2] , axis = 1) result = result.loc[:, ~result.columns.str.contains('^Unnamed')] result = result.loc[:, ~result.columns.str.contains('^index')] result.to_csv('{}_labels.csv'.format(n_classes)) print(result) return result