首页 > 解决方案 > 用查找表 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()是一个很好的功能,但我无法弄清楚如何将它应用到这个场景中。提前致谢。

标签: pythonpandaslookupdata-manipulation

解决方案


上面的大多数答案都在使用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.


推荐阅读