Home > OS >  python how to call class by using list
python how to call class by using list

Time:11-22

i would like to take values of a list (created by using pandas - xlsx) and put them into a class of objects / instances.

my current code looks like:

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))


the output of the list looks like this:

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

if i call the class manually like: test = Asset("host1", "2312312", "New York") it works. But not by using the list. No error messages. Could someone help me, please? Where is my mistake?

input dataframe:

  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

CodePudding user response:

Assuming this input:

  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

You can use apply:

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

or, if there are already the three columns in order:

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

output:

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

To assign to a new column:

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

output:

  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>
  • Related