如何將其組合到單個函式并將所有值附加到單個 df
我的試驗是在網路函式中創建 df_network,然后在記憶體函式中創建 df_memory,然后嘗試連接兩個不同的 df。
這有效
def network():
df_network = pd.DataFrame(
([i.DNSHostName, i.ipaddress] for i in conn.Win_ddd()),
columns=['DNSHostName', 'ipaddress']
)
return df
def memory():
df_memory = pd.DataFrame(
([i.Caption, i.TotalPhysicalMemory] for i in conn.Win_sss()),
columns=['Caption', 'TotalPhysicalMemory']
)
return df
df_network = network()
df_memory = memory()
像這樣的東西,但我在下面的試驗中得到錯誤 - 如果我嘗試單一功能
def total():
df = pd.DataFrame(
([i.DNSHostName, i.ipaddress] for i in conn.Win_ddd()),
columns=['DNSHostName', 'ipaddress']
([i.Caption, i.TotalPhysicalMemory] for i in conn.win_sss()),
columns=['Caption', 'TotalPhysicalMemory']
)
return df
df.head()
| DNSHostName | ipaddress | Caption | TotalPhysicalMemory |
|-------------|--------------|---------|---------------------|
| AAA | xx.xx.xxx.xx | RRR | 3434334 |
| BBB | xx.xx.xxx.aa | FFF | 6456456 |
uj5u.com熱心網友回復:
這里最簡單的解決方案是使用pd.concatwithaxis=1來組合兩個資料幀:
def total():
df = pd.concat([
pd.DataFrame(
([i.DNSHostName, i.ipaddress] for i in conn.Win_ddd()),
columns=['DNSHostName', 'ipaddress']
),
pd.DataFrame(
([i.Caption, i.TotalPhysicalMemory] for i in conn.Win_sss()),
columns=['Caption', 'TotalPhysicalMemory']
)
], axis=1)
return df
df_total = total()
uj5u.com熱心網友回復:
我認為這將滿足您的要求:
class Ddd:
def __init__(self, DNSHostName, ipaddress):
self.DNSHostName = DNSHostName
self.ipaddress = ipaddress
class Sss:
def __init__(self, Caption, TotalPhysicalMemory):
self.Caption = Caption
self.TotalPhysicalMemory = TotalPhysicalMemory
ddd = [Ddd('host' str(i), '000.00.0000') for i in range(5)]
sss = [Sss('caption' str(i), 100000000000) for i in range(5)]
def total():
df = pd.DataFrame(
([i.DNSHostName, i.ipaddress] for i in ddd),
columns=['DNSHostName', 'ipaddress']
)
df[['Caption', 'TotalPhysicalMemory']] = pd.DataFrame([i.Caption, i.TotalPhysicalMemory] for i in sss)
return df
print(total())
輸出:
DNSHostName ipaddress Caption TotalPhysicalMemory
0 host0 000.00.0000 caption0 100000000000
1 host1 000.00.0000 caption1 100000000000
2 host2 000.00.0000 caption2 100000000000
3 host3 000.00.0000 caption3 100000000000
4 host4 000.00.0000 caption4 100000000000
uj5u.com熱心網友回復:
您可以使用chain.from_iterable:
from itertools import chain
d1 = [[i.DNSHostName, i.ipaddress] for i in conn.Win_ddd()]
d2 = [[i.Caption, i.TotalPhysicalMemory] for i in conn.Win_sss()]
cols = ['DNSHostName', 'ipaddress', 'Caption', 'TotalPhysicalMemory']
df = pd.DataFrame((chain.from_iterable(i) for i in zip(d1, d2)), columns=cols)
輸出:
>>> df
DNSHostName ipaddress Caption TotalPhysicalMemory
0 AAA a.b.c.d RRR 3434334
1 BBB e.f.g.h FFF 6456456
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/451791.html
上一篇:有沒有辦法減少此類中的回圈數量?
