我有一個使用資料框的兩列創建的串列。我需要創建一個字典,其中鍵是串列的元素,值是資料框中列的元素。下面是我剛剛創建的一個示例。我使用的資料框很大,串列也是如此。
data={'init':[1,2,1], 'term':[2,3,3], 'cost':[10,20,30]}
df=pd.DataFrame.from_dict(data)
link=[(1,2),(1,3),(2,3) ]
我需要使用資料框和串列創建以下字典。
link_cost={(1,2): 10,(1,3):30,(2,3):20,}
有人可以幫我解決這個問題嗎?任何意見或指示將不勝感激。
uj5u.com熱心網友回復:
讓我們試試set_index reindex然后Series.to_dict:
d = df.set_index(['init', 'term'])['cost'].reindex(index=link).to_dict()
d:
{(1, 2): 10, (1, 3): 30, (2, 3): 20}
set_index多列將創建一個可以用元組索引的 MultiIndex。選擇特定列,然后reindexing將允許串列link重新排序/選擇系列中的特定值。Series.to_dict將創建字典輸出。
使用的設定:
import pandas as pd
df = pd.DataFrame({
'init': [1, 2, 1],
'term': [2, 3, 3],
'cost': [10, 20, 30]
})
link = [(1, 2), (1, 3), (2, 3)]
uj5u.com熱心網友回復:
為什么你甚至為此使用熊貓?您dict有權:
link_cost = dict(zip(link, data['cost']}}
# or if you must use the dataframe it's the same
link_cost = dict(zip(link, df['cost']}}
{(1,2): 10, (2,3):20, (1,3):30}
uj5u.com熱心網友回復:
一種方法是使用DataFrame.set_index,Index.isin和DataFrame.itertuples:
import pandas as pd
data = {'init': [1, 2, 1], 'term': [2, 3, 3], 'cost': [10, 20, 30]}
df = pd.DataFrame.from_dict(data)
link = [(1, 2), (2, 3), (1, 3)]
cols = ["init", "term"]
new = df.set_index(cols)
res = dict(new[new.index.isin(link)].itertuples(name=None))
print(res)
輸出
{(1, 2): 10, (2, 3): 20, (1, 3): 30}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/347799.html
