Reputation: 1955
I have following dataframe and i want to search apple in column fruits and display all the rows if apple is found.
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
Upvotes: 0
Views: 161
Reputation: 153460
Use groupby
and filter
to filter groups that contain '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,'')
Output:
number fruits purchase
0 0 apple yes
1 mango
2 banana
3 1 apple no
4 cheery
7 3 apple yes
8 orange
Upvotes: 1
Reputation: 3130
It looks like you're using 'number'
as the index, so I'm going to assume that.
Get the numbers where 'apple'
is present, and slice into those:
idx = df.index[df.fruits == 'apple']
df.loc[idx]
Upvotes: 0