gpt4 book ai didi

python - 使用python将excel数据导入到类实例中

转载 作者:太空宇宙 更新时间:2023-11-04 00:02:56 24 4
gpt4 key购买 nike

我正在尝试将数据从 Excel 工作表导入到 RPG 游戏的类实例列表中。目前我正在尝试使用 Pandas,这是我一直在使用的代码:python 3.7.2

import pandas as pd


class potion(object):

def __init__(self, name, types, effects, value, weight):
self.name = name
self.types = types
self.effects = effects
self.value = value
self.weight = weight

df = pd.read_excel('Data/potions.xlsx', sheet_name='None')

potions = df.values.tolist()

print(potions)

输出为:

[['Crude Hp Potion', 'Hp Potion', 10, 10, 0.5], ['Hp Potion', 'Hp Potion', 
25, 50, 1.0], ...]

我正在寻找的一个例子是要像这样存储的数据,这样每一行都是它自己的实例列表索引:

potions = [potion('Crude Hp Potion', 'Hp Potion', 10, 10, 0.5),
potion('Hp Potion', ' hp Potion', 25, 50, 1.0)]

为了实现我的尝试:

for i in potions[0]:
potions.append([potion(i)])

print(potions[0].name)

并给了我:

TypeError: __init__() missing 4 required positional arguments: 'types', 'effects', 'value', and 'weight'

我正在处理的excel表中的数据如下:

                 Name       Type  Effect  Price  Weight
0 Crude Hp Potion Hp Potion 10 10 0.5
1 Hp Potion Hp Potion 25 50 1.0
2 Superior Hp Potion Hp Potion 50 100 1.5
3 Crude Mp Potion Mp Potion 5 5 0.5
4 Mp Potion Mp Potion 15 50 1.0
5 Superior Mp Potion Mp Potion 30 100 1.5

我不太确定我错过了什么,希望得到帮助,我似乎找不到任何地方可以解释如何做到这一点。谢谢。

最佳答案

你已经非常接近了,你只需要从你的 potion 列表中解压列表中的所有值。这可以用星号 (*) 来完成。这样,您的药水对象将被称为 potion(arg1, arg2, arg3, arg4, arg5),这是正确的,而不是 potion([arg1, arg2, arg3, arg4, arg5]),这会引发您发现的错误(因为列表表示单个对象)。

以下代码更正了这一点:

class Potion(object): 
def __init__(self, name, types, effects, value, weight):
self.name = name
self.types = types
self.effects = effects
self.value = value
self.weight = weight

df = pd.read_excel('Data/potions.xlsx', sheet_name='None')

potions = df.values.tolist()
potion_instances = []
for p in potions:
potion_instances.append(Potion(*p))

我冒昧地稍微修改了你的结构。首先,给你的对象更有意义的名字,这样你就不会混淆 - potionpotions 非常接近,按照惯例,Python 类总是用 CamelCase 编写。此外,迭代列表 potion 并将每个创建的 Potion 对象附加到新列表(我将其命名为 potion_instances)更有意义。这样一来,您就可以将原始数据和代码对象彼此分开。

关于python - 使用python将excel数据导入到类实例中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55113379/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com