首页 > 解决方案 > 我有一个混合整数字符串列:如何只更改字符串?

问题描述

我有一个数据框,其中有一列名为Text. 该列的行均采用以下格式:

xxx - some sentence 

其中xxx是一个随机数。我所拥有的一个例子是:

      Text
100 - Hello World
200 - Bye World
300 - Good World

我希望 python 仅查找字符串字符(“某些句子”)并将其替换为我指定的值。我目前使用的方法是:

mapping = {"100 - Hello World":"100 - Bonjour Le Monde"}
df = df.replace({"Text":mapping})

这适用于小型数据集,但该数据集有 15k+ 个条目和多个随机数。我宁愿不必每次都指定每个数字。如何告诉 python 找到字符串并只翻译字符串?

非常非常感谢你!

标签: pythonstringpandasdataframereplace

解决方案


regex=True

mapping = {"Hello World": "Bonjour Le Monde"}
df.replace({"Text":mapping}, regex=True)

                     Text
0  100 - Bonjour Le Monde
1         200 - Bye World
2        300 - Good World

推荐阅读