python - 用查找表 df 中的值替换 Pandas 系列中的多个字符串
问题描述
我有一个这样的 DataFrame,其中type
列是用以下分隔的字符串~
:
id | types |
---------------
1 | A1~B1 |
2 | B1 |
3 | A1~A2~B2 |
我需要根据如下所示的查找表替换“类型”列中的字符串,其中两列都是字符串。这样做时,我需要确保最终输出在types
.
type | description |
------------------------
A1 | This is good |
A2 | This is OK |
B1 | This is not good |
B2 | This is bad |
所以最终的输出是这样的:
id | types |
--------------------------------------------
1 | This is good, This is not good |
2 | This is not good |
3 | This is good, This is OK, This is bad |
我读过这.map()
是一个很好的功能,但我无法弄清楚如何将它应用到这个场景中。提前致谢。
解决方案
上面的大多数答案都在使用apply
,它不会矢量化。我建议使用str.replace
:
string_map = {
'A1': 'This is good',
'A2': 'This is OK',
'B1': 'This is not good',
'B2': 'This is bad',
'~': ', '
}
df = pd.DataFrame([{'type': 'A1~B1'}, {'type': 'B1'}, {'type': 'A1~A2~B2'}])
df_desc = df.copy()
for key, value in string_map.items():
df_desc['type'] = df_desc['type'].str.replace(key, value)
在这里,我假设映射字典中的映射数量远小于 DataFrame 中的行数。
如果你string_map
在 DataFrame 中有你的(调用它df_map
),你可以通过运行以下命令从它创建一个字典string_map = df_map.set_index('type')['description'].to_dict()
:确保您{type: '~', 'description': ', '}
的df_map
.
推荐阅读
- php - 有没有办法让 Y 轴不适应谷歌柱形图的加载表?
- javascript - Angular js文本剪辑,如果文本超过150个字符,则会被剪辑
- mysql - MySQL 插入时出现错误 1022。怎么修?
- c# - 我可以同时在 Azure 存储中创建和保存文件吗?
- visual-studio-code - 创建 VS Code Java 项目不创建 .project 或 .classpath
- cakephp - CakePHP 4.x - 如何烘焙 Twig 模板?
- python - 对带有精灵的 2d 数组(板)进行深度复制
- spring - Spring Boot - MongoDb 通过手动创建的查询查找
- python - glClearColor 返回负值?(溢出?)
- javascript - 如何在不使用 npm 或 nodejs 的情况下捆绑 javascript 文件?[ 独立的 javascript 捆绑器 ]