首页 > 解决方案 > 用满足 Column1 条件的字典键替换 Column2 值

问题描述

我有一本将数字标签与分类标签相关联的字典。

dict = {
0:'cat',
1:'dog', 
2:'fish
}

我的数据框(df)输出如下所示:

Feature  | Feature Value | Feature1 |  Feature1 Value

Pet        1               Thing       1
Person     Steve           Pet         1
Place      Texas           Place       Virginia

我想用“狗”替换“1”。

我试过这个。

df.replace({df.loc[df['Feature'] == 'Pet']: dict})

但是,我知道这只是查看匹配 Feature 列,而不是从 Feature 值中提取值以在字典中匹配。

我的数据框(df)输出应该是:

Feature  | Feature Value | Feature1 |  Feature1 Value

Pet        dog             Thing       1
Person     Steve           Pet         dog
Place      Texas           Place       Virginia

标签: pythonpandasnumpy

解决方案


考虑到您的情况,您可以这样做:

df['Feature Value'].map(dict).fillna(df['Feature Value'])

这是根据您在字典中定义的标签的非详尽映射和map()函数映射,而 fillna() 有助于保留不匹配的现有值。而且,map()repalce()


推荐阅读