Home > Net >  How to filter data using an function? - Python
How to filter data using an function? - Python

Time:12-31

I'am trying to so something simple, just use a function to call loc from pandas and then print it in an excell sheet, but I don't know why the output is empty.

def update_output(farol,dias,prod,officer,anal,coord):
    df_f=df.loc[(df['FarolAging'].isin([farol])) & (df['Dias Pendentes'].isin([dias])) & (df['Produto'].isin([prod])) & (df['Officer'].isin([officer])) & (df['Analista'].isin([anal])) & (df['Coordenador'].isin([coord]))]
    df_f.to_excel('C:\\Users\\brechtl\\Downloads\\File.xlsx', index=False)

update_output('vermelho', 'Até 20 dias','','Alexandre Denardi','Guilherme De Oliveira Moura','Anna Claudia')

Edit: As asked by a friend at the comments, I created a similar dataframe as the one I'am using

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

CodePudding user response:

You have not passed value for third parameter while calling function. Is it by mistake or intentional? This could result in NO data, as all filter conditions are in "AND", means all must be true.

CodePudding user response:

On the basis that you want to want to have optional values passed to the function then I think you need to use a function within the selection. The model code below shows how this might work (using == for the comparison).

def test(row, val1, val2):
    if val1 == '':
        val1 = row['col1']
    if val2 == '':
       val1 = row['col2']
    if row['col1'] == val1 and row['col2'] == val2:
        return True
    else: 
        return False
    
def func(x1, x2):
    df_f = df.loc[df.apply((lambda x: test(x, x1, x2)), axis = 1)]
    return df_f


print(func('', 'dd'))

gives

  col1 col2
0   aa   dd

print(func('aa', 'dd'))

gives

  col1 col2
0   aa   dd

print(func('xx', 'dd'))

gives empty dataframe

  • Related