python - 用满足 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
解决方案
考虑到您的情况,您可以这样做:
df['Feature Value'].map(dict).fillna(df['Feature Value'])
这是根据您在字典中定义的标签的非详尽映射和map()
函数映射,而 fillna() 有助于保留不匹配的现有值。而且,map()
比repalce()
推荐阅读
- scala - 带有 flatbuffers 的 Akka-grpc 怎么样?
- postgresql - 访问 postgres docker 容器时出现连接错误
- python - asyncpg - 如果不存在,则连接到服务器并创建数据库
- unity3d - 尝试合并两个着色器(双面和横截面)但出现语法错误
- rest - 无法找出正确的 Bitbucket REST API 1.0 - 仍然获得 http 404
- java - 无法从本地目录读取excel文件
- node.js - Docker MongoDB 收到元数据后立即关闭连接
- javascript - 我怎样才能弄清楚为什么这个计时器功能不起作用
- reactjs - 如何在反应js中的每个url中的域后添加哈希
- iis - 如何将 web.config 配置为 301 将所有 index.php 请求重定向到默认主页?