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

标签 python pandas dataframe

我有以下格式的字典:

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/

相关文章:

python - 使用 Anaconda 在 Windows 上使用 pytest githook

python - 如何使用用于 clang 工具的 python 绑定(bind)来判断类/结构是可复制的

python - 帮助错误信息

python - 如何根据两个不同列上设置的某些条件填充 pandas 数据框中的列?

r - 为什么 mapply 不能按预期使用转换?

python - 如何在一张图中绘制两个颜色相同但线条样式不同的 pandas DataFrame?

python - 如何从 Pandas DataFrame 的列内列表中删除值

Python 相当于 label2idx MATLAB 函数

python - 将 Pandas 数据框列和索引转换为值

python - 如何绘制 Pandas 计数的分组条形图