我有一本字典,它将数字标签与分类标签相关联。
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})
但是,我知道这只是查看匹配特征列,而不是从特征值中提取值以在字典中进行匹配。
我的 dataframe(df) 输出应该是:
Feature | Feature Value | Feature1 | Feature1 Value
Pet dog Thing 1
Person Steve Pet dog
Place Texas Place Virginia
最佳答案
考虑到您的情况,您可以这样做:
df['Feature Value'].map(dict).fillna(df['Feature Value'])
这是非详尽的映射,map()
函数根据您在字典中定义的标签进行映射,fillna() 有助于保留不匹配的现有值。此外,map()
比 repalce()
快得多
关于python - 将 Column2 值替换为满足 Column1 条件的字典键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57299829/