How to extract previous and current rows if their value is equal - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Data Science (https://python-forum.io/forum-44.html) +--- Thread: How to extract previous and current rows if their value is equal (/thread-11019.html) |
How to extract previous and current rows if their value is equal - SriRajesh - Jun-18-2018 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')] RE: How to extract previous and current rows if their value is equal - gontajones - Jun-18-2018 df={'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]} filtered_df = {'Name': [], 'Rank': [], 'Score': []} for i in range(len(df['Name'])): try: if df['Name'][i] == 'MM' and df['Name'][i+1] == 'MA': filtered_df['Name'].append(df['Name'][i]) filtered_df['Name'].append(df['Name'][i+1]) filtered_df['Rank'].append(df['Rank'][i]) filtered_df['Rank'].append(df['Rank'][i+1]) filtered_df['Score'].append(df['Score'][i]) filtered_df['Score'].append(df['Score'][i+1]) except: pass print(filtered_df) RE: How to extract previous and current rows if their value is equal - SriRajesh - Jun-18-2018 I still want to put the data in pandas dataframe RE: How to extract previous and current rows if their value is equal - gontajones - Jun-18-2018 I'm not sure if I understood what you're asking for, maybe this: import pandas as pd 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]}) filtered_df = {'Name': [], 'Rank': [], 'Score': []} for i in range(len(df['Name'])): try: if df['Name'][i] == 'MM' and df['Name'][i+1] == 'MA': filtered_df['Name'].append(df['Name'][i]) filtered_df['Name'].append(df['Name'][i+1]) filtered_df['Rank'].append(df['Rank'][i]) filtered_df['Rank'].append(df['Rank'][i+1]) filtered_df['Score'].append(df['Score'][i]) filtered_df['Score'].append(df['Score'][i+1]) except: pass filtered_pd_df = pd.DataFrame(filtered_df) print(filtered_pd_df) RE: How to extract previous and current rows if their value is equal - SriRajesh - Jun-18-2018 I used as below: pd.DataFrame.from_dict(filtered_df), but your comment also works, Many many thanks RE: How to extract previous and current rows if their value is equal - volcano63 - Jun-18-2018 (Jun-18-2018, 02:49 PM)SriRajesh Wrote: Hi, Enumerate was redundant
|