我想獲取串列的值(通過使用 pandas - xlsx 創建)并將它們放入一類物件/實體中。
我當前的代碼看起來像:
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']
如果我手動呼叫該類,例如:
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
uj5u.com熱心網友回復:
假設這個輸入:
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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/362551.html
