1

I have a dataset using pandas in python and would like to apply an if-then-else rule for a specific column.

If the there is missing value, then replace it with a specific value taken from another column in the same observation, else do nothing.

My dataset is generated by the code as follow:

results = df2.merge(df1,on="sku", how="left")

The column variable that needs to be filled, if empty is "stock_y". If empty, the value of the column variable "stock_x" should be copied to "stock_y". In the case that stock_y is already filled, the code should skip the observation.

1
  • Look into fillna. Ps your post will probably be downvoted if you don't post sample data. Commented Sep 22, 2019 at 11:21

2 Answers 2

2

Check out Series.combine_first:

results['stock_y'] = results['stock_y'].combine_first(results['stock_x'])
Sign up to request clarification or add additional context in comments.

Comments

0

Implementation with fillna:

results['stock_y'] = results['stock_y'].fillna(results['stock_x'])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.