繁体   English   中英

Pandas替换DataFrame中的第一个结果

[英]Pandas Replace 1st Result in a DataFrame

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

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

我想输出的是:

            Q      R
0   breakfast  a.txt
1       apple  a.txt
2      orange  a.txt
3   breakfast  b.txt
4      orange  b.txt

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

有没有办法做到这一点?

这是一个带有groupbyidxmin的矢量化解决方案:

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

我真的很想回答这个问题。

def swap_first(s):
  swap = 1
  luk4 = {'apple'}
  for x in s:
    if x.lower() in luk4 and swap:
      yield 'breakfast'
      swap ^= 1
    else:
      yield x
      if x not in luk4:
        swap ^= 1

df4.assign(Q=[*swap_first(df4.Q)])

           Q      R
0  breakfast  a.txt
1      apple  a.txt
2     orange  a.txt
3  breakfast  b.txt
4     orange  b.txt

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM