只替换datafram中列的第一个字符

2024-04-24 09:21:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图替换出现在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

尝试过:

^{pr2}$

所需最终输出:

                                    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

Tags: thetotestdffortodayisour
2条回答

不知道为什么另一个答案被删除了,它更简洁,而且起到了作用。(对不起,我不记得是谁发的。我试过了答案,但也有一定的局限性)

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,读起来不像人类。您需要告诉Python按空格分割。例如,通过^{}

df = pd.DataFrame({'some_text': ['ur goal is to finish shopping for books today',
                                 'Our goal is to finish shopping for books today',
                                 'The help is on the way',
                                 'he way is clear … he is going to library']})

d = {'ur': 'Our', 'he': 'The'}

df['result'] = [' '.join((d.get(i, i), j)) for i, j in df['some_text'].str.split(n=1)]

print(df)

                                        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   

                                           result  
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  

相关问题 更多 >