我在Pandas数据帧中有一列,我想用它在查找字典中查找成本值。
我的想法是,如果项目存在,我将更新现有的列,如果不存在,该列将保留为空。
到目前为止,我看到的所有方法和解决方案似乎都创建了一个新列,比如apply和assign方法,但保留现有数据很重要。
下面是我的代码:
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]},)
我想要实现的是查找水果列中的项目,如果项目在那里,我希望使用乘以件数的字典值来更新cost列。
例如,对于Apple,查找字典中的成本是1,而数据帧中的块数量是6,因此成本列将从88更新为( 6 *1) =6。下一项是不在查找字典中的香蕉,因此原始数据帧中的成本将保持不变。相同的逻辑将应用于其余的项目。
我能想到的实现这一点的唯一方法是将列表从dataframe中分离出来,遍历它们,然后在完成时将它们添加回dataframe中。我想知道是否有可能在不使用单独列表的情况下对数据帧中的值执行操作??
从其他响应中,我想象我必须使用loc指示器,如下所示:(但这不起作用,我不想创建一个新的专栏)
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
发布于 2017-08-11 16:07:26
如果我理解正确的话:
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
https://stackoverflow.com/questions/45639196
复制相似问题