How to clear lines on pandas using a list as a filter?

Asked

Viewed 80 times

1

Given the df as indicated below (could be a greater good), I would like to delete in df the data of the lines according to the list 'listFilter'.

nome = ['foo','bar','fiz','zaz','foo','far','bar','fiz','cdd','boo','zuz','zuz']
valor = [2,3,2,5,6,7,2,9,6,3,8,10]

listaFiltro = ['zuz', 'boo']

df = pd.DataFrame({'nome': nome, 'valor': valor})
    nome    valor
0   foo     2
1   bar     3
2   fiz     2
3   zaz     5
4   foo     6
5   far     7
6   bar     2
7   fiz     9
8   cdd     6
9   boo     3
10  zuz     8
11  zuz     10

I’ve tried to use it that way here but unsuccessfully:

df = df.drop(df[df.nome] != listaFiltro.index)

2 answers

0


Importing and creating lists with values:

import pandas as pd

nome = ['foo','bar','fiz','zaz','foo','far','bar','fiz','cdd','boo','zuz','zuz']
valor = [2,3,2,5,6,7,2,9,6,3,8,10]

listaFiltro = ['zuz', 'boo']

Creating the data frame:

df = pd.DataFrame({'nome': nome, 'valor': valor})

Keeping only values that are not in the Tier list:

df1 = df[~df['nome'].isin(listaFiltro)]
df1

The ~ sign indicates the values that are not inside the filter. It’s always good practice to create new data frame when making changes, so you always keep the main data frame intact.

0

As you demonstrate that answer, you can use the pandas.DataFrame.isin.

df = df[~df['nome'].isin(listaFiltro)]

With this command, you are replacing your dataframe df by dataframe df where the values in the column nome are not in listaFiltro.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.