gpt4 book ai didi

python - Pandas 使用查找字典更新列中的值

转载 作者:太空宇宙 更新时间:2023-11-03 14:55:08 26 4
gpt4 key购买 nike

我在 Pandas 数据框中有一列,我想用它来在查找字典中查找成本值。

这个想法是,如果该项目存在,我将更新现有列,否则该列将留空。

到目前为止我看到的所有方法和解决方案似乎都创建了一个新列,例如 apply 和 allocate 方法,但保留现有数据很重要。

这是我的代码:

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。下一项是香蕉它不在查找字典中,因此原始数据帧中的成本将保持不变。相同的逻辑将应用于其余项目。

我能想到实现此目的的唯一方法是将列表与数据帧分开,迭代它们,然后在完成后将它们添加回数据帧。我想知道是否可以在不使用单独列表的情况下对数据框中的值进行操作?

从其他回复中,我想象我必须使用如下所示的 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

最佳答案

如果我理解正确的话:

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

关于python - Pandas 使用查找字典更新列中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45639196/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com