[英]Python: Convert Edgelist from NetworkX into dataframe
作為使用 Networkx 的結果,我有一個奇怪的數據結構(不知道它是列表還是元組)。 我需要將其轉換為數據幀。
我擁有的“列表”具有以下結構:
[('a', 'a', {'weight': 2}),
('a', '!', {'weight': 0}),
('a', 'c', {'weight': 2}),
('a', 'b', {'weight': 1}),
('a', 'q', {'weight': 1}),
('a', 's', {'weight': 2}),... ]
我需要一個數據框,如下所示:
Inf Prov Weight
a a 2
a ! 0
a c 2
a b 1
a q 1
a s 2
有人可以幫我嗎?
在創建數據幀之前先稍微簡化一下數據可能是最簡單的。 根據為您提供初始數據的操作(元組列表,每個元組包含 2 個字符串和一個 dict),可能讓該操作為您提供簡化的數據。 但如果這是不可能的——或者更一般地說,當您無法控制給定庫生成的數據結構時,您可以進行一些簡單的操作,例如:
import pandas as pd
# initial data from qu
raw_data = [('a', 'a', {'weight': 2}),
('a', '!', {'weight': 0}),
('a', 'c', {'weight': 2}),
('a', 'b', {'weight': 1}),
('a', 'q', {'weight': 1}),
('a', 's', {'weight': 2}),]
# transform data to extract the value of each weight
data = [(elem1, elem2, d_elem.get('weight', 0)) for (elem1, elem2, d_elem) in raw_data]
# put together the dataframe from the list of records
df = pd.DataFrame.from_records(data, columns=['Inf', 'Prov', 'Weight'])
print(df)
根據需要給出結果:
Inf Prov Weight
0 a a 2
1 a ! 0
2 a c 2
3 a b 1
4 a q 1
5 a s 2
如果未定義,則使用dict.get
允許我們指定默認值,而不是引發 KeyError。
import pandas as pd
x=[('a', 'a', {'weight': 2}),
('a', '!', {'weight': 0}),
('a', 'c', {'weight': 2}),
('a', 'b', {'weight': 1}),
('a', 'q', {'weight': 1}),
('a', 's', {'weight': 2})]
inf_list=list([])
prov_list=list([])
weight_list=list([])
for tuple in x:
inf_list.append(tuple[0])
prov_list.append(tuple[1])
weight_list.append(tuple[2])
df=pd.DataFrame()
df['inf']=inf_list
df['prov']=prov_list
df['weight']=weight_list
df['weight']=df['weight'].map(lambda x:x['weight'])
print(df)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.