【问题标题】:Stuck using pandas to build RPG item generator卡住使用 pandas 构建 RPG 项目生成器
【发布时间】:2020-12-03 22:09:26
【问题描述】:

我正在尝试为我正在开发的游戏构建一个简单的随机项目生成器。 到目前为止,我一直在试图弄清楚如何存储和访问所有数据。我与 pandas 一起使用 .csv 文件来存储数据集。

我想为生成的项目添加加权概率,因此我尝试读取 csv 文件并将每个列表编译成一个新集合。

我让程序选择一个随机集合,但在尝试从该集合中提取随机行时卡住了。

当我使用 .sample() 拉出项目行时出现错误,这让我觉得我不明白 pandas 的工作原理。我认为我需要创建新列表,以便以后可以索引并在选择项目后访问项目的各种统计信息。

一旦我拉出我打算添加可以改变伤害和护甲等显示的效果的项目。所以我在考虑让新项目成为它自己的列表,然后使用damage = item[2] + 3 或我需要的任何东西

错误是:AttributeError: 'list' object has no attribute 'sample'

谁能帮助解决这个问题?也许有更好的方法来设置数据?

到目前为止,这是我的代码:

import pandas as pd
import random 

df = [pd.read_csv('weapons.csv'), pd.read_csv('armor.csv'), pd.read_csv('aether_infused.csv')]

def get_item():
    item_class = [random.choices(df, weights=(45,40,15), k=1)] #this part seemed to work. When I printed item_class it printed one of the entire lists at the correct odds
    item = item_class.sample()
    print (item) #to see if the program is working
get_item()

【问题讨论】:

  • 我想知道 read_csv 函数是否不是这里需要的......

标签: python-3.x pandas dataframe generator


【解决方案1】:

我认为您对列表与列表元素有些混淆。这应该有效。我用简单的 dfs 存根你的 dfs

import pandas as pd
import random 

# Actual data. Comment it out if you do not have the csv files 
df = [pd.read_csv('weapons.csv'), pd.read_csv('armor.csv'), pd.read_csv('aether_infused.csv')]

# My stubs -- uncomment and use this instead of the line above if you want to run this specific example
# df = [pd.DataFrame({'weapons' : ['w1','w2']}), pd.DataFrame({'armor' : ['a1','a2', 'a3']}), pd.DataFrame({'aether' : ['e1','e2', 'e3', 'e4']})]

def get_item():
    # I removed [] from the line below -- choices() already returns a list of length 1
    item_class = random.choices(df, weights=(45,40,15), k=1) 

    # I added [0] to choose the first element of item_class which is a list of length 1 from the line above
    item = item_class[0].sample()
    print (item) #to see if the program is working
get_item()

从我设置的随机数据帧中打印随机行,例如

  weapons
1      w2

【讨论】:

  • 嗯...我可以在这种方法中使用我的武器、盔甲和以太数据集吗?我试图避免在每个列表中输入数百个项目
  • @KevinMcGreal 我不明白你的问题。你的 csvs 中有你的数据框吗?我将它们编码为示例,因为我没有您的 csv,但您将它们加载到您的问题中。所以你应该用你的问题中的df = ... 行替换我的df = ...
  • 原谅我的无知。我仍然只有几个月的时间来学习 python 并且不知道该怎么称呼一切。在这段代码中我应该在哪里插入我的 csv 文件?
  • 没问题!都去过那里。我编辑了我的答案,因此它应该适用于您的实际数据。如果您想查看它是否适用于我的示例数据,请按照代码中的“注释此取消注释”说明进行操作
  • 它的工作!所以现在我想弄清楚如何,例如,从一个项目中提取伤害,以便我可以在 GUI 上显示它,并在添加效果后在必要时添加到它。我尝试 print (item[3]) 看它是否会显示一个值但得到一个 KeyError
猜你喜欢
  • 2015-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-04
  • 2020-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多