gpt4 book ai didi

python - Pandas:根据行内容定位和更新值

转载 作者:行者123 更新时间:2023-11-28 16:26:51 30 4
gpt4 key购买 nike

我有以下格式的字典:

MyDict = {"string1" : 10, "string2" : 20, "string3" : 30, ...}

我还有一个具有以下格式的大型 DataFrame:

  col1              col2  
0 string1 1
1 string2 2
2 string3 1
3 string1 3
4 string3 4
5 string1 5

我想找到 col1 != string1 的值,并根据行内容和我最初提到的字典更改值:

df.loc[df["col1"] != "string1" , "col2"] = df["col2"] * MyDict[df["col1"]]

(我立即意识到上述 loc 的用法是不可能的,果然:Series 的对象是可变的,因此它们不能被散列)

所需输出的表示:

  col1              col2  
0 string1 1
1 string2 40
2 string3 30
3 string1 3
4 string3 120
5 string1 5

在 Pandas 中处理这个问题的正确方法是什么?

最佳答案

使用map在 bool 掩码 df 上传递将执行查找并将列与返回系列的结果相乘的字典:

In [273]:
MyDict = {"string1" : 10, "string2" : 20, "string3" : 30}
df.loc[df["col1"] != "string1" , "col2"] *= df['col1'].map(MyDict)
df

Out[273]:
col1 col2
0 string1 1
1 string2 40
2 string3 30
3 string1 3
4 string3 120
5 string1 5

关于python - Pandas:根据行内容定位和更新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35892330/

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