I have 12 columns of ingredients and 12 respective columns of measurements of those ingredients. For some rows the ingredients are specified but the measurements are not i.e. they are NA. I want to set up a condition such that if a certain ingredient entry is not NA and the corresponding entry is NA, set the corresponding measurement entry to 1.
cols1 = ["strIngredient1","strIngredient2","strIngredient3","strIngredient4","strIngredient5","strIngredient6",
"strIngredient7","strIngredient8","strIngredient9","strIngredient10","strIngredient11","strIngredient12"]
cols2 = ["strMeasure1","strMeasure2","strMeasure3","strMeasure4","strMeasure5","strMeasure6","strMeasure7",
"strMeasure8","strMeasure9","strMeasure10","strMeasure11","strMeasure12"]
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
if a certain ingredient entry is not NA and the corresponding entry is NA, set the corresponding entry to 1
If I understand correctly, you can use mask to replace values where the condition is True.
for col1, col2 in zip(cols1, cols2):
df[col2] = df[col2].mask(df[col1].notna()&df[col2].isna(), 1)
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0