Home > Software design >  Pandas drop() deletes every rows that has same id number
Pandas drop() deletes every rows that has same id number

Time:08-20

I have a datameframe like below. I want to drop all grade F's from the dateframe but when I write the code below, It drops all same ID numbers as well. In this case all id number 101 is deleted. but I want to keep only status passed. Only grade F is failed.

df.drop(df.index[df['Grade'] == 'F'], inplace=True)

ID Lesson Status Grade
101 Math Passed A
545 History Passed B
789 English Failed F
101 History Failed F
475 Math Passed C
689 Enlish Passed D

CodePudding user response:

It'd be better to just create and use mask, rather than what you are doing i.e. filtering using index and then dropping

>>> df[df.Grade.ne('F')]
      Lesson  Status Grade
ID                        
101     Math  Passed     A
545  History  Passed     B
475     Math  Passed     C
689   Enlish  Passed     D

CodePudding user response:

unless I don't understand what you are trying to do, you can simply do:

df2 = df[df['Grade'] != 'F']

df2
ID  Lesson  Status  Grade
0   101 Math    Passed  A
1   545 History Passed  B
4   475 Math    Passed  C
5   689 Enlish  Passed  D
  • Related