Pandas替换DataFrame中的第一个结果

Lun*_*Box 2 python python-3.x pandas

假设我有一个如下所示的数据框:

df4

df4 = pd.DataFrame({'Q':['apple', 'apple', 'orange', 'Apple', 'orange'], 'R':['a.txt', 'a.txt', 'a.txt', 'b.txt', 'b.txt']})

>>> df4



        Q      R
0   apple  a.txt
1   apple  a.txt
2  orange  a.txt
3   Apple  b.txt
4  orange  b.txt
Run Code Online (Sandbox Code Playgroud)

我想输出的是:

            Q      R
0   breakfast  a.txt
1       apple  a.txt
2      orange  a.txt
3   breakfast  b.txt
4      orange  b.txt
Run Code Online (Sandbox Code Playgroud)

换句话说,不区分大小写,我想搜索数据帧中的每一行,找到某些单词的第一个出现(在这种情况下,该单词是apple),并将其替换为另一个单词.

有没有办法做到这一点?

cs9*_*s95 6

这是一个带有groupby和的矢量化解决方案idxmin:

v = df.Q.str.lower().eq('apple')    
v2 = (~v).cumsum().where(v)
df.loc[v2.groupby(v2).idxmin().values, 'Q'] = 'breakfast'

df
           Q      R
0  breakfast  a.txt
1      apple  a.txt
2     orange  a.txt
3  breakfast  b.txt
4     orange  b.txt
Run Code Online (Sandbox Code Playgroud)