0

I'm attempting to use a lambda, along with a function, to search and return a specific value from a dataframe. Any idea how to procede? Is there a way to pass the entire df into the lambda, or is that bad practice? I've attached my attempted code here. any help would be greatly appreciated

My code is based on this:https://stackoverflow.com/a/66145080/10671347 except my data frame has values that sometimes repeat, and sometimes a row will now have value I'm searching forenter image description here

def    getvalue(col1value,col2value): #i check to see if col1value matches a hard coded value, and if so, I return a single value from the original dataframe
        if colvalue1=='HardcodedValue':
           return df.loc[df['col2']==colvalue2,col3value].iloc[0] #fetches value, since it returns a series i grab the first match
        else:
           return 0
    
    df['new']=df.apply(lambda row: getvalue(row['col1'],row['col2']))
     
randomUser
  • 11
  • 4
  • it is bad practice, because there are native methods that will use the underlying `c` code to run much faster than vanilla python loops. could you post your input dataframe as well as the target your trying to achieve? also see [when should i (not) use apply](https://stackoverflow.com/questions/54432583/when-should-i-not-want-to-use-pandas-apply-in-my-code#:~:text=I%20have%20also%20seen%20a,should%20be%20avoided%20if%20possible.) – Umar.H Apr 19 '21 at 21:21
  • thanks @Umar.H I've attached a screenshot of the data frame. essentially If you will notice id 1 does not have a status code when it has status 'a', however it receives status code 'z' when it becomes status 'b' later on. I am attempting to ad status code 'z' to the first row. Later on id4 may also have a status code, lets say 'x' and I would like to attach 'x' to id4, but only if id 4 does in fact receive a status code later on – randomUser Apr 19 '21 at 21:28
  • i think you can use `fillna` or `bfill()` with `ffill()` forward fill and back fill respectively. try `df.replace('', np.nan,regex=True).groupby('col1 (ids)')['statuscode'].bfill()` if you need to forward fill just chain `.ffill()` at the end. – Umar.H Apr 19 '21 at 22:10
  • p.s a screen shot is _not_ a [mcve] you need to add a textual example of your dataframe for others to reproduce. – Umar.H Apr 19 '21 at 22:11

0 Answers0