2017-08-11 29 views
0

我在Pandas數據框中有一列,用於在查找字典中查找成本值。Pandas使用查找字典更新列中的值

這個想法是,如果項目存在,我將更新現有的列,如果不存在,列將留空。

到目前爲止,我所見過的所有方法和解決方案似乎都創建了一個新列,例如應用和分配方法,但重要的是我保留現有數據。

這裏是我的代碼:

lookupDict = {'Apple': 1, 'Orange': 2,'Kiwi': 3,'Lemon': 8} 

df1 = pd.DataFrame({'Fruits':['Apple','Banana','Kiwi','Cheese'], 
       'Pieces':[6, 3, 5, 7], 
       'Cost':[88, 55, 65, 55]},) 

我想實現的是查找在果欄,如果項目的項目有我想更新與詞典值乘以數量的費用列件。

例如,對於Apple,查找字典的成本爲1,在數據框中,數量爲6,因此成本列將從88更新爲(6 * 1)= 6.下一項是不在查找字典中的香蕉,因此原始數據框中的成本將保持不變。相同的邏輯將應用於其餘的項目。

我認爲實現這一目標的唯一方法是將列表與數據框分開,遍歷它們,然後在完成時將它們添加回數據框。我想知道是否可以在不使用單獨列表的情況下對數據框中的值進行操作?

從其他的回答,我像我必須使用組委會指標如下列:(但是這是行不通的,我不希望創建一個新的列)

df1.loc[df1.Fruits in lookupDict,'Cost'] = lookupDict[df1.Fruits] * lookupD[df1.Pieces] 

我也曾嘗試映射但它覆蓋現有列的所有內容:

df1['Cost'] = df1['Fruits'].map(lookupDict)*df1['Pieces'] 

編輯*******

我已經能夠使用如下的迭代以實現它,但是我我仍然好奇,如果有,是實現這一清潔方法:

#Iteration method 

for i,x in zip(df1['Fruits'],xrange(len(df1.index))): 
     fruit = (df1.loc[x,'Fruits']) 
     if fruit in lookupDict: 
      newCost = lookupDict[fruit] * df1.loc[x,'Pieces'] 
      print(newCost) 
      df1.loc[x,'Cost'] = newCost 

回答

1

IIUC:

mask = df1['Fruits'].isin(lookupDict.keys()) 
df1.loc[mask, 'Cost'] = df1.loc[mask, 'Fruits'].map(lookupDict) * df1.loc[mask, 'Pieces'] 

Result: 

In [29]: df1 
Out[29]: 
    Cost Fruits Pieces 
0  6 Apple  6 
1 55 Banana  3 
2 15 Kiwi  5 
3 55 Cheese  7