我正在尝试替换数据框中每一行中语句开头出现的某些单词。但是,传入“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/