python 如何使用列表调用 class

python how to call class by using list

我想获取列表的值(使用 pandas - xlsx 创建)并将它们放入 class 个对象/实例中。

我当前的代码如下:

import pandas as pd
import os
cwd = os.path.abspath('')
files = os.listdir(cwd)

class Asset():
    """ class to create assets """
    
    def __init__(self, hostname, serial_number, city):
        self.hostname = hostname
        self.serial_number   = serial_number
        self.city   = city
        

df = pd.read_excel('some_assets.xlsx', sheet_name='Tabelle1') 
df1 = df[['hostname', 'serial_number', 'city']]
potions = df1.values.tolist()
potion_instances = []
for p in potions:
    print (p)
    potion_instances.append(Asset(*p))


列表的输出如下所示:

['host1', 2312312, 'New York']
['host2', 423213, 'New York']
['host3', 24313213, 'Stuttgart']
['host4', 3213213, 'Rom']
['host5', 1542312, 'Rom']
['host6', 42112421, 'Stuttgart']

如果我像这样手动调用 class: test = Asset("host1", "2312312", "New York") 有效。但不是通过使用列表。没有错误信息。有人可以帮我吗?我的错误在哪里?

输入数据帧:

  hostname  serial_number       city
0    host1        2312312   New York
1    host2         423213   New York
2    host3       24313213  Stuttgart
3    host4        3213213        Rom
4    host5        1542312        Rom
5    host6       42112421  Stuttgart

假设输入:

  hostname  serial_number       city
0    host1        2312312   New York
1    host2         423213   New York
2    host3       24313213  Stuttgart
3    host4        3213213        Rom
4    host5        1542312        Rom
5    host6       42112421  Stuttgart

您可以使用 apply:

df[['hostname', 'serial_number', 'city']].apply(lambda r: Asset(*r), axis=1)

或者,如果三列已经按顺序排列:

df.apply(lambda r: Asset(*r), axis=1)

输出:

0  host1    <__main__.Asset object at 0x7f9d28b7a220>
1  host2    <__main__.Asset object at 0x7f9d28b7aa00>
2  host3    <__main__.Asset object at 0x7f9d28c472e0>
3  host4    <__main__.Asset object at 0x7f9d28c47190>
4  host5    <__main__.Asset object at 0x7f9d28c473d0>
5  host6    <__main__.Asset object at 0x7f9d28c474c0>
dtype: object

要分配给新列:

df['new_col'] = df.apply(lambda r: Asset(*r), axis=1)

输出:

  hostname  serial_number       city                                    new_col
0    host1        2312312   New York  <__main__.Asset object at 0x7f9d28bd6e20>
1    host2         423213   New York  <__main__.Asset object at 0x7f9d28bd62b0>
2    host3       24313213  Stuttgart  <__main__.Asset object at 0x7f9d28bd6820>
3    host4        3213213        Rom  <__main__.Asset object at 0x7f9d28bd6e80>
4    host5        1542312        Rom  <__main__.Asset object at 0x7f9d28bd6370>
5    host6       42112421  Stuttgart  <__main__.Asset object at 0x7f9d28bd64f0>