Jun-18-2018, 08:09 PM
(Jun-18-2018, 02:49 PM)SriRajesh Wrote: Hi,
I want to extract rows if the previous row of Name column equal to 'MM' and current row of Name column is 'MA'
import pandas as pd import numpy as np df=pd.DataFrame({'Name':['MM','MA','CS','MM','MM','TH','MM','MA'],'Rank':[1,3,3,1,2,3,2,2],'Score':[120,20,12,15,2,83,22,32]}) for i,(index,row) in enumerate(df.iterrows()): if i == 0: continue df[(df.Name.loc[i]=='MA') & (df.Name.loc[i-1]=='MM')]
Output:print(list(df.iterrows()))
[(0, Name MM
Rank 1
Score 120
Name: 0, dtype: object), (1, Name MA
Rank 3
Score 20
Name: 1, dtype: object), (2, Name CS
Rank 3
Score 12
Name: 2, dtype: object), (3, Name MM
Rank 1
Score 15
Name: 3, dtype: object), (4, Name MM
Rank 2
Score 2
Name: 4, dtype: object), (5, Name TH
Rank 3
Score 83
Name: 5, dtype: object), (6, Name MM
Rank 2
Score 22
Name: 6, dtype: object), (7, Name MA
Rank 2
Score 32
Name: 7, dtype: object)]
Enumerate was redundant
Test everything in a Python shell (iPython, Azure Notebook, etc.)
- Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
- Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
- You posted a claim that something you did not test works? Be prepared to eat your hat.