python - 交换 Pandas 字符串列中的两个子字符串

标签 python python-3.x pandas dataframe

我想用 Pandas DataFrame 中的字符串本身的一部分替换字符串。

例子:

MSc Joe L. Scott 更改为 Joe L. Scott MSc

所以只需要移动MSc。我可以用正则表达式解决这个问题,但不知道如何用 Pandas DataFrame 来解决这个问题

result = re.sub(r'(MSc)(.*)' , r'\2 \1',s)

我在想这样的事情(但是这里的 to_replacevalue 是什么?):

['Name_modified'].replace(regex=True, inplace=True, to_replace= **??**, value=**??**)

或者使用DataFrame.sub()

但是尽管有文档我还是没有完成

最佳答案

作为一个人为的例子,考虑

df = pd.DataFrame({'Name' : ['MSc Joe L. Scott', 'BSc J. Doe']})
df
               Name
0  MSc Joe L. Scott
1        BSc J. Doe

您可以在此处使用带有反向引用的 str.replace。这可以轻松处理多个不同的名称。

designations = ['MSc', 'BSc']
df['Name_modified'] = df['Name'].str.replace(
    rf"^({'|'.join(designations)})\s(.*)$", r"\2 \1")

df
               Name     Name_modified
0  MSc Joe L. Scott  Joe L. Scott MSc
1        BSc J. Doe        J. Doe BSc

您可以将此结果分配回去。

关于python - 交换 Pandas 字符串列中的两个子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53800557/

相关文章:

python正则表达式适用于在线测试仪但不适用于程序

python - 删除 Pandas 中的 DataFrame 行,其中列表中的列值

python - 合并和转换两个 Pandas 数据框

Python:发送带有嵌入式图像和附件的多部分 html 电子邮件

python - aioredis + aiohttp 正确使用连接池

python - 保存从数组中删除的数字的位置

python - 如何让 virtualenv 在 mac 上的 python3 上工作

python - 将 pandas DataFrame query() 方法与 isin() 结合起来

python - 未定义 DISPLAY 时使用 matplotlib 生成 PNG

python - 重新排列字符串/列表的所有方法的列表