Skip to main content
 首页 » 编程设计

python之在数据框中搜索组合以更改单元格值

2025年04月02日8bonelee

如果两列中的值组合有效,我想替换列中的值。假设我有以下 DataFrame

df = pd.DataFrame([ 
        ['Texas 1', '111', '222', '333'], 
        ['Texas 1', '444', '555', '666'], 
        ['Texas 2', '777','888','999'] 
    ]) 
 
         0    1    2    3 
0  Texas 1  111  222  333 
1  Texas 1  444  555  666 
2  Texas 2  777  888  999 

如果我想替换 column 2 中的值,如果 column 0 = Texas 1 和 column 2 = 222I '正在执行以下操作:

df.ix[ (df.Column 0=='Texas 1')&(df.Column 2 =='222'),Column 2] = "Success"  

这适用于一些组合。我迷路的部分是如何针对 300 多种组合执行此操作?我想也许我可以使用 dict 并存储 key ,这将是 'Success' 或任何其他值。列表可以是组合。有点像这样。

a["Success"] = [Texas 1, 222] 
>>> a 
{"Success": [Texas 1, 222]} 

但我不确定如何在 DataFrame 中执行此操作。

请您参考如下方法:

您几乎拥有所有代码,只需创建 dictionary 或 list 并对其进行迭代即可完成。

import pandas as pd 
combinations = [['key1', 'key2', 'msg']] 
combinations.append(['Texas 1', '222', 'triple two']) 
combinations.append(['Texas 1', '555', 'triple five']) 
 
df = pd.DataFrame([ 
        ['Texas 1', '111', '222', '333'], 
        ['Texas 1', '444', '555', '666'], 
        ['Texas 2', '777','888','999'] 
    ]) 
 
for c in combinations: 
    df.ix[(df[0] == c[0]) & (df[2] == c[1]), 1] = c[2] 

输出:

         0            1    2    3 
0  Texas 1   triple two  222  333 
1  Texas 1  triple five  555  666 
2  Texas 2          777  888  999