我正在尝试根据类属性动态地向我的pandas.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中保存最后一个位置。
答案 0 :(得分:1)
您的实施存在一些问题。
<强>代码:强>
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