簡體   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