我试图替换出现在dataframe中每一行的语句的第一个字。但是,传入“1”位置将替换所有内容。为什么在replace中传递“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
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”)开头的所有起始字符。在正确的代码是:
“
^
”表示行的开头&应该只替换行开头的不完整单词。'\s
表示第一个单词后面有一个空格,因此它只匹配正确的单词。在编程语言,包括Python,读起来不像人类。您需要告诉Python按空格分割。例如,通过^{} :
相关问题 更多 >
编程相关推荐