2017-03-01 14 views
0

クラス属性に基づいてpandas.DataFrameに行を動的に追加しようとしていますが、何らかの理由で機能しません。うまくいけば、一例では、より理にかなって:私は最初の移動と別々の行の第二の動きを保存する一方でこれは、二度同じ動きを出力クラス属性に基づいてDataFrameに動的に行を追加する

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) 

。ムーブが実行されるたびに、新しい位置をmatch1.movesの行に保存し、最後の位置をmatch1.positionに保存します。

答えて

1

実装にはいくつか問題がありました。

  1. あなたは各行のユニークなボードのスナップショットをしたい場合は、データフレームをしたい場合は、self.moveはリスト
  2. すべきではない、あなたはボードにあなたがそれを保存するたびにコピーする必要があります。

コード:

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

テストコード:

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) 

結果:

[[ 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 
関連する問題