简体   繁体   中英

Conditional Iteration over a Pandas Dataframe using Function

every month I get a dataframe, so every month I will have to do some adjusts to the dataframe, I would like to create a function for just apply it on every dataframe without create the code again. I have for the first dataframe, called enero:

for i in range(0,len(enero)):
    if enero.loc[i,"VENDEDOR_CLIENTE"] == "ARTURO":
        enero.loc[i,"MARCA"]="MAQUILA PINTUCO"
    elif enero.loc[i,"PROVEEDOR"] == "PEPITO" and enero.loc[i,"VENDEDOR_CLIENTE"] != "ARTURO":
        enero.loc[i,"MARCA"]="PINTURAS"

For the second dataframe, called febrero:

for i in range(0,len(febrero)):
    if febrero.loc[i,"VENDEDOR_CLIENTE"] == "ARTURO":
        febrero.loc[i,"MARCA"]="MAQUILA PINTUCO"
    elif febrero.loc[i,"PROVEEDOR"] == "PEPITO" and febrero.loc[i,"VENDEDOR_CLIENTE"] != "ARTURO":
        febrero.loc[i,"MARCA"]="PINTURAS"

So, as not to repeat the code every month, I would like to create a function:

def ajustemarca(df,VENDEDOR_CLIENTE,MARCA,PROVEEDOR):
    for i in range(0,len(df)):
        if df.loc[i,"VENDEDOR_CLIENTE"] == "ARTURO":
            df.loc[i,"MARCA"]="MAQUILA PINTUCO"
        elif df.loc[i,"PROVEEDOR"] == "PEPITO" and df.loc[i,"VENDEDOR_CLIENTE"] != "ARTURO":
            df.loc[i,"MARCA"]="PINTURAS"
    return df.loc[i,"MARCA"]

Then, I am calling the function:

enero.apply(ajustemarca)
febrero.apply(ajustemarca)

But, it does not work. How can I do this function?

I share an answer that someone wrote here, but it was deleted:(

The answer was perfect and now the code work:

def ajustemarca(df):
    for i in range(0,len(df)):
        if df.loc[i,"VENDEDOR_CLIENTE"] == "ARTURO":
            df.loc[i,"MARCA"]="MAQUILA PINTUCO"
        elif df.loc[i,"PROVEEDOR"] == "PEPITO." and df.loc[i,"VENDEDOR_CLIENTE"] != "ARTURO":
             df.loc[i,"MARCA"]="PINTURAS"
ajustemarca(enero)
ajustemarca(febrero)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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