当函数运行n次时,如何将函数的字典输出放入数据帧中?



所以我为特定的游戏模拟编写了这个函数。我已经从我的代码中删除了不相关的部分。

def play(games=1):
for j in range (1,games+1):
from itertools import chain
Player1,Player2=deal()
#print(Player1,Player2)
l1=[]
l2=[]
l3=[]
l4=[]
count = 0
for i in range(0,26,2):
.
.
.
Stats={'Initial total of Player 1 ':sum(Player1),
'Initial total of Player 2 ':sum(Player2),
'Number of Ties ':count,
'Maximum round total won ':max(l4),
'Final total of Player 1 ':sum(l1),
'Final total of Player 2 ':sum(l2)}
print (Stats)

因此,play()会给出{'Initial total of Player 1 ': 185, 'Initial total of Player 2 ': 179, 'Number of Ties ': 0, 'Maximum round total won ': 40, 'Final total of Player 1 ': 229, 'Final total of Player 2 ': 135}作为输出。

同样,play(2)也会给{'Initial total of Player 1 ': 164, 'Initial total of Player 2 ': 200, 'Number of Ties ': 0, 'Maximum round total won ': 34, 'Final total of Player 1 ': 76, 'Final total of Player 2 ': 288}{'Initial total of Player 1 ': 179, 'Initial total of Player 2 ': 185, 'Number of Ties ': 1, 'Maximum round total won ': 43, 'Final total of Player 1 ': 155, 'Final total of Player 2 ': 209}.这里的"2"作为参数表示游戏模拟的数量。

现在我需要如何将每个字典插入到pandas数据帧中,其中字典的索引将是列,值将是行。因此,例如,"5"游戏模拟意味着具有 5 个数据行的数据帧,每次生成字典时一个数据行。

嗨,欢迎来到 StackOverflow!

问题是我们正在运行一个循环而不是保存值。我们只是打印它们。尝试以下操作:

def play(games=1):
rounds = []
for j in range (1, games + 1):
from itertools import chain
Player1, Player2 = deal()
#print(Player1,Player2)
l1 = []
l2 = []
l3 = []
l4 = []
count = 0
for i in range(0,26,2):
.
.
.
stats = {'Initial total of Player 1 ':sum(Player1),
'Initial total of Player 2 ':sum(Player2),
'Number of Ties ':count,
'Maximum round total won ':max(l4),
'Final total of Player 1 ':sum(l1),
'Final total of Player 2 ':sum(l2)}
print(stats)
rounds.append(stats)
return rounds

现在,当您运行此函数时,它将返回字典列表。每个字典包含一个数据行的值。

data_rows = play()

要将其转换为数据框,请执行以下操作:

df = pd.DataFrame.from_records(data_rows)

最新更新