简体   繁体   中英

Python Functions with multiple arguments

I have written the following code

def createv(dsn,vname,benchdsn,benchvar):
    #global grp
    for t in range(len(dsn)):
        w=dsn[vname].iloc[t]
        #print(w)
        for index in range(len(benchdsn)):
            #print(index)
            z = benchdsn[benchvar].iloc[index]
            #print(z)
            if w <= z:
                grp = z
                print(grp)
                break     
            else:
                continue
    return grp

recent_sample['carvaluegrp2']= createv(recent_sample,'CarValue',df6,'carvalueU')

The issue is that for the newly created variable carvaluegrp2, all values are the same - which is the last value of CarValue from recent_sample. I tried to use map() and apply() functions, but I am getting syntax errors. All I want is to have appropriate value - which the function is returning for each record of CarValue - as a value in the variable carvaluegrp2.

You need to append your result to a running list like this:

def createv(dsn,vname,benchdsn,benchvar):
    result = []
    for t in range(len(dsn)):
        w=dsn[vname].iloc[t]
        #print(w)
        for index in range(len(benchdsn)):
            #print(index)
            z = benchdsn[benchvar].iloc[index]
            #print(z)
            if w <= z:
                grp = z
                print(grp)
                break     
            result.append(grp)
    return result

Also, you never need else: continue . It's the same as having the if statement without an else.

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