Pandas 在数据框列中搜索值

Pandas 在数据框列中搜索值,pandas,Pandas,我有以下数据框,我想在列水果中搜索苹果,如果找到苹果,则显示所有行 Before : number fruits purchase 0 apple yes mango banana 1 apple no cheery 2 mango yes banana 3 apple

我有以下数据框,我想在列水果中搜索苹果,如果找到苹果,则显示所有行

Before : 
   number fruits     purchase
    0       apple     yes
            mango
            banana
    1       apple     no
            cheery      
    2       mango     yes
            banana
    3       apple     yes
            orange
    4       grapes    no
            pear

After:            
    number fruits     purchase
    0       apple     yes
            mango
            banana
    1       apple     no
            cheery      
    3       apple     yes
            orange

看起来您使用的是
'number'
作为索引,所以我假设是这样的

获取“苹果”所在的数字,并将其切分为:

idx = df.index[df.fruits == 'apple']
df.loc[idx]

使用
groupby
filter
筛选包含“apple”的组:

df['number'] = df['number'].ffill()

df.groupby('number').filter(lambda x: (x['fruits'] == 'apple').any())

df_out.assign(number = df_out['number'].mask(df.number.duplicated()))\
  .replace(np.nan,'')
输出:

  number  fruits purchase
0      0   apple      yes
1          mango         
2         banana         
3      1   apple       no
4         cheery         
7      3   apple      yes
8         orange         

水果列类型是列表还是字符串?水果列类型是objecti我没有使用数字作为索引。