-1

I'm aware that you can use df1 = df1[df1['Computer Name'] != 'someNameToBeDropped'] to drop a given string as a row

what if i wanted to do it the other way around. Let's say dropping everything except what i have in a list of strings.

is there a simple hack I haven't noticed?

Daniel Saggo
  • 108
  • 1
  • 9
  • `df1 = df1[df1['Computer Name'] == 'someNameNOTToBeDropped']` ? – harvpan Aug 20 '19 at 19:12
  • 1
    @harvpan has the correct solution but, `~` is an interesting operator. `df1[~(df1['Computer Name'] != 'someNameToBeDropped')]` – Scott Boston Aug 20 '19 at 19:15
  • 1
    harv has the correct solution given there are only two names in the column's possible values. For `n` values, `~` is the way to go ;p – rafaelc Aug 20 '19 at 19:17
  • NB: all good above but I prefer to use `loc` as it is a vectorized built in method `df1 = df1.loc[~(df1['Computer Name'] != 'someNameToBeDropped'), :]` – Benoit Drogou Aug 20 '19 at 19:19
  • But does it drop everything else except 'someNameNOTToBeDropped' ? – Daniel Saggo Aug 20 '19 at 19:27
  • Dropping everything except something = Looking for something. `df1[df1['Computer Name'] == 'someNameNOTToBeDropped']` with `==` returns rows with `ComputerName` = `someNameNOTToBeDropped`. Use `df.loc[df['col'].isin(mylist)]` for multiple strings. – harvpan Aug 20 '19 at 19:30
  • Alright, thank you everyone for the answers – Daniel Saggo Aug 20 '19 at 19:38

1 Answers1

3

Try this to get rows such that value of col is in that given list

df = df[df[column].isin(list_of_strings)]

Additional to exclude what's in the list

df = df[~df[column].isin(list_of_values)]
Parijat Bhatt
  • 664
  • 4
  • 6