Filter Pandas dataframe with user input

Question:

I’m trying to develop this code where I would have certain inputs for different variables, these would make the filter happen and return the filtered dataframe, this input will always only receive a single value that the user will choose amoung fewer options and if the input is empty, that filter must bring all the data.

I didn’t put the user input because I was testing the function first, however, the function always returns an empty dataframe and I can’t find out why. Here is the code I was developing:

I didn’t put the dataframe because it comes from an excel, but if necessary I’ll put together a sample that fits


df = pd.DataFrame({"FarolAging":["Vermelho","Verde","Amarelo"],"Dias Pendentes":["20 dias","40 dias","60 dias"],"Produto":["Prod1","Prod1","Prod2"],
"Officer":["Alexandre Denardi","Alexandre Denardi","Lucas Fernandes"],"Analista":["Guilherme De Oliveira Moura","Leonardo Silva","Julio Cesar"],
"Coord":["Anna Claudia","Bruno","Bruno"]})

FarolAging1 = ['Vermelho']
DiasPendentes = []
Produto = []
Officer = []

def func(FarolAging1,DiasPendentes,Produto,Officer):

    if len(Officer) <1:
        Officer = df['Officer'].unique()

    if len(FarolAging1) <1:
        FarolAging1 = df['FarolAging'].unique()

    if len(DiasPendentes) <1:
        DiasPendentes = df['Dias Pendentes'].unique()

    if len(Produto) <1:
        Produto = df['Produto'].unique()


    dados2 = df.loc[df['FarolAging'].isin([FarolAging1]) & (df['Dias Pendentes'].isin([DiasPendentes])) & (df['Produto'].isin([Produto])) & (df['Officer'].isin([Officer]))]
    print(dados2)

func(FarolAging1, DiasPendentes, Produto, Officer) ```

Answers:

You have to remove the square brackets in isin because you already have lists:

def func(FarolAging1,DiasPendentes,Produto,Officer):

    if len(Officer) <1:
        Officer = df['Officer'].unique()

    if len(FarolAging1) <1:
        FarolAging1 = df['FarolAging'].unique()

    if len(DiasPendentes) <1:
        DiasPendentes = df['Dias Pendentes'].unique()

    if len(Produto) <1:
        Produto = df['Produto'].unique()


    # Transform .isin([...]) into .isin(...)
    dados2 = (df.loc[df['FarolAging'].isin(FarolAging1)
              & (df['Dias Pendentes'].isin(DiasPendentes))
              & (df['Produto'].isin(Produto))
              & (df['Officer'].isin(Officer))])
    print(dados2)
    return dados2  # don't forget to return something

Output:

>>> func(FarolAging1, DiasPendentes, Produto, Officer)

  FarolAging Dias Pendentes Produto            Officer                     Analista         Coord
0   Vermelho        20 dias   Prod1  Alexandre Denardi  Guilherme De Oliveira Moura  Anna Claudia
Answered By: Corralien