python - 仅替换数据框中列的第一个字符

标签 python string python-3.x pandas dataframe

我正在尝试替换数据框中每一行中语句开头出现的某些单词。但是,传入“1”位置会替换所有内容。为什么在替换中传递“1”不起作用?对此有不同的方法吗? 谢谢!

初始:

df_test = pd.read_excel('sample.xlsx')
print('Initial: \n',df_test)

Initial: 
                                         some_text
0   ur goal is to finish shopping for books today
1  Our goal is to finish shopping for books today
2                          The help is on the way
3        he way is clear … he is going to library

尝试过:

df_test['some_text'] = df_test['some_text'] \
        .str.replace('ur ','Our ',1) \
        .str.replace('he ','The ',1) 
print('Tried:\n',df_test)

Tried: (Incorrect Results) 
                                          some_text
0   Our goal is to finish shopping for books today
1  OOur goal is to finish shopping for books today
2                          TThe help is on the way
3        The way is clear … he is going to library

需要的最终输出:

                                    some_text
0   Our goal is to finish shopping for books today
1  Our goal is to finish shopping for books today
2                          The help is on the way
3        The way is clear … he is going to library

最佳答案

不知道为什么另一个答案被删除了,它更简洁并且完成了工作。 (抱歉,我不记得是谁发布的。我尝试了这个答案并且有效但有一定的局限性)

df.some_text.str.replace('^ur','Our').str.replace('^he','The')

但是,正如评论中指出的那样,这将替换所有以“ur”(“ursula”)或“he”(“helen ').

更正后的代码是:

df.some_text.str.replace('^ur\s','Our ').str.replace('^he\s','The ')

'^' 表示行首 & 应该只替换行首的不完整单词。 '\s' 表示第一个单词后有一个空格,因此它只匹配正确的单词。

关于python - 仅替换数据框中列的第一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53597796/

相关文章:

python - BeautifulSoup 解析

python - 在矩形内绘制线宽 matplotlib

Python:用字符串中的整数替换 "wrong" float

javascript - 如何判断一个字符串是否是日期格式?

Python 内部中断函数

python - 反转文件中的第一个字节

regex - 如何使用python脚本在linux中压缩多个文件?

python - 通过 python 对 Twitter 社交图进行爬虫

java - 在 Java 中查找可变数量的字符串数组的乘积

c# - C# 中的 Ironpython 导入模块导入 csv 模块时出错