Filter lines in pandas by a list

Asked

Viewed 4,270 times

0

Given the dataframe below, I would like to filter the data of the lines according to the list 'listFilter'.

    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   zoo     6
9   boo     3
10  zuz     8
11  zuz     10

listaFiltro = ['fiz', 'zoo', 'far']

Thanks in advance for the help of friends!

  • 2

    Ever tried to make?

2 answers

1

In a very simplified way, Voce can use this:

def listaFiltro(dataframe, primeiro, segundo, terceiro):
       return dataframe[(dataframe['nome']==primeiro) | (dataframe['nome'] == segundo) | (dataframe['nome'] == terceiro)]
df_teste = listaFiltro('fiz', 'zoo', 'far')
df_teste

Example 2:

In this case to pass a variable list, you can use the function isin as is below.

def listaFiltro(dataframe, valores):
    return dataframe.loc[dataframe['nome'].isin(valores)]
lista = ['fiz', 'zoo', 'far']
dfteste = listaFiltro(df, lista)
dfteste
  • Thanks for the reply, friend! But imagine a list of 20 items? There is no such thing as : df[filter(items=listFilter, Axis=0) ], but it would work logically?

  • mrzappabr, adjusted response to need, I believe this is what you are looking for.

  • 1

    Exactly Clayton, much simpler. It could have done in several other ways, but you must agree that this last one is the most "elegant". I tried to give a vote on your answer but, since I’m new, I couldn’t. Anyway, I thank you for your help.

  • Of course much more elegant, and say 'Correct' rs. No problem no friend, the important thing is that it worked and that’s what counts. If possible just mark the answer as correct so that other people can be helped.

  • 1

    As I have already said, unfortunately, I can’t vote. But I gave an UP anyway. Clayton Hugging !

-2

Taking the example provided by Clayton, it can be done directly, without using function:

x = dfteste.loc[dfteste['nome'].isin(['fiz','zoo','far'])] print(x)

  • 1

    Greetings Daniel, it seems that this has already been presented in another answer. Have some other consideration that might enhance the discussion?

Browser other questions tagged

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