简体   繁体   English

如何使用 function 过滤数据? - Python

[英]How to filter data using an function? - Python

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.我正在尝试做一些简单的事情,只需使用 function 从 pandas 调用 loc 然后将其打印在 excell 表中,但我不知道为什么 output 是空的。

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编辑:正如评论中的一位朋友所问,我创建了一个与我正在使用的类似的 dataframe

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"])

You have not passed value for third parameter while calling function. Is it by mistake or intentional?调用function时第三个参数没有传值,是误传还是故意的? This could result in NO data, as all filter conditions are in "AND", means all must be true.这可能导致没有数据,因为所有过滤条件都在“AND”中,意味着所有条件都必须为真。

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.基于您希望将可选值传递给 function 那么我认为您需要在选择中使用 function。 The model code below shows how this might work (using == for the comparison).下面的 model 代码显示了它是如何工作的(使用 == 进行比较)。

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给空 dataframe

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM