繁体   English   中英

根据class属性向DataFrame动态添加行

[英]Add row dynamically based on the class attribute to a DataFrame

我试图基于类属性向我的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中。

您的实现存在两个问题。

  1. 如果要使用DataFrame,则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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM