Home > Blockchain >  Lambda Function in python for my Purchase dataset
Lambda Function in python for my Purchase dataset

Time:02-24

I have my data set where I have to fill the missing values in the Column "Extended Price" with a formula with other columns that is = Quantity Ordered * Unit Cost. I have tried this function it works but keep changing for me the non missing values from their original values to 0 because of else part.

How do I keep the values for the non missing values and use the function only to make changes on the missing values.

Here is my code function.

df['Extended Cost'] = df.apply(lambda var: var['Quantity Ordered'] * var['Unit Cost'] if var['Extended Cost'] != var['Extended Cost'] else 0, axis=1) 

Suggestions and help are appreciated.

CodePudding user response:

Set the value equal to itself in the else case. that way you aren't changing the data if it exists.

Also your if condition should be around the other way around, i.e. do something if the value is None, else do nothing

df['Extended Cost'] = df.apply(lambda var: var['Quantity Ordered'] * var['Unit Cost'] if var['Extended Cost'] == None else var['Extended Cost'], axis=1)

CodePudding user response:

I think you shouldn't use .apply here, .fillna seems better suited for that job:

df['Extended Cost'] = df['Extended Cost'].fillna(
    df['Quantity Ordered'] * df['Unit Cost']
)
  • Related