简体   繁体   中英

Add row dynamically based on the class attribute to a DataFrame

I am trying to dynamically add a line to my pandas.DataFrame based on the class attributes, but it does not work for some reason. Hopefully an example makes more sense:

import numpy as np
import pandas as pd

class match:
def __init__(self):
    self.position = np.zeros(shape = (3, 3))
    self.moves = []

def PlayMove(self, x_coordinate, y_coordinate, player_name):
    if player_name == "player1":
        self.position[x_coordinate, y_coordinate] = 1
    if player_name == "player2":
        self.position[x_coordinate, y_coordinate] = 4
    self.moves.append(pd.DataFrame(self.position.reshape(1, 9)))

match1 = match()
match1.PlayMove(1,2,"player1")
print(match1.position)
print(match1.moves)
match1.PlayMove(2,2,"player1")
print(match1.position)
print(match1.moves)

This outputs same move twice, while I want to save the first move and the second move in a seperate rows. Every time a move is played I want to save the new position in a row in match1.moves and the last position in match1.position.

There were a couple of issues with your implementation.

  1. If you want a DataFrame, self.move should not be a list
  2. If you want unique board snapshots in each row, then you need to copy the board every time you save it.

Code:

class match:
    def __init__(self):
        self.position = np.zeros(shape=(3, 3))
        self.moves = None

    def PlayMove(self, x_coordinate, y_coordinate, player_name):
        if player_name == "player1":
            self.position[x_coordinate, y_coordinate] = 1
        else:
            self.position[x_coordinate, y_coordinate] = 4
        move = pd.DataFrame(np.array(self.position).reshape(1, 9))
        self.moves = pd.concat([self.moves, move])

Test Code:

match1 = match()
match1.PlayMove(1, 2, "player1")
print(match1.position)
print('\n1:\n', match1.moves)
match1.PlayMove(2, 2, "player2")
print('\n', match1.position)
print('\n2:\n', match1.moves)

Results:

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

1:
     0    1    2    3    4    5    6    7    8
0  0.0  0.0  0.0  0.0  0.0  1.0  0.0  0.0  0.0

[[ 0.  0.  0.]
 [ 0.  0.  1.]
 [ 0.  0.  4.]]

2:
     0    1    2    3    4    5    6    7    8
0  0.0  0.0  0.0  0.0  0.0  1.0  0.0  0.0  0.0
0  0.0  0.0  0.0  0.0  0.0  1.0  0.0  0.0  4.0

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