Anmol Parida
Anmol Parida

Reputation: 688

Delete Rows where there are multiple conditions on columns

Please use the below code for the dataframe.

Delete all Rows where ['Sachin', 'Virat'] scord more than 100 in the year '2014'


smd = [['Sachin', 1989, 130],
       ['Virat', 2014, 99],
       ['Sachin', 2014, 99],
       ['Virat', 2014, 183],
       ['Virat', 2014, 183],
       ['Rohit', 2014, 79],
       ['Virat', 2015, 129],
       ['Raina', 2014, 183],
       ['Rohit', 2014, 264],
       ['Sachin', 2014, 130],] 
df_smd = pd.DataFrame(smd, columns = ['Player', 'Year','Score'])
df_smd

Upvotes: 0

Views: 44

Answers (1)

Alexandre B.
Alexandre B.

Reputation: 5502

You just need to write your conditions:

  1. To get an equality, you can use df.column_name == your_value
  2. To select rows which are in a list, isin do the job.
  3. To inverse the condition, use ~ operator.

Once you have the conditions, you can applied all them with & operator (and not and).

Here the code:

smd = [['Sachin', 1989, 130],
       ['Virat', 2014, 99],
       ['Sachin', 2014, 99],
       ['Virat', 2014, 183],
       ['Virat', 2014, 183],
       ['Rohit', 2014, 79],
       ['Virat', 2015, 129],
       ['Raina', 2014, 183],
       ['Rohit', 2014, 264],
       ['Sachin', 2014, 130]]
df_smd = pd.DataFrame(smd, columns=['Player', 'Year', 'Score'])

# Select row where player is 'Sachin' or 'Virat'
condition_name = df_smd.Player.isin(['Sachin', 'Virat'])
condition_score = df_smd.Score > 100
condition_year = df_smd.Year == 2014

# Apply all the conditions
output = df_smd[~(condition_name & condition_score & condition_year)]
print(output)
#    Player  Year  Score
# 0  Sachin  1989    130
# 1   Virat  2014     99
# 2  Sachin  2014     99
# 5   Rohit  2014     79
# 6   Virat  2015    129
# 7   Raina  2014    183
# 8   Rohit  2014    264

You can also do it with drop (even if I found it less natural..):

condition = (condition_name & condition_score & condition_year)
output = df_smd.drop(index=condition[condition].index)
print(output)
#    Player  Year  Score
# 0  Sachin  1989    130
# 1   Virat  2014     99
# 2  Sachin  2014     99
# 5   Rohit  2014     79
# 6   Virat  2015    129
# 7   Raina  2014    183
# 8   Rohit  2014    264

Upvotes: 1

Related Questions