Home > Back-end >  Check for null values in if statement
Check for null values in if statement

Time:11-16

I am very new to Python, and I wanted to ask a question about how to check the null values as condition in if statement. I am not sure how to construct the syntax. Hopefully someone can help me to solve the problem. Thank you so much, and wish you all have a wonderful day.

So here is problem. I am working with a dataframe, and I want to sort my row first on condition, then do the calculation, the dataframe is look like that: Column A Column B 0 1 2 3 4 5 ...

I want to calculate the average of Column A and Column B, but if Column A is null, the average will be Column B, and when Column B is null, average will be Column A. The Code that I constructed is following:

if df['A'].notnull is True & df['B'].notnull is True:
    df['Avg']=df['A'].astype(float)/2   df['B'].astype(float)/2
elif df['A'].notnull is True & df['B'].isnull is True:
    df['Avg']=df['A'].astype(float)
else df['A'].isnull is True & df['B'].notnull is True:
    df['Avg']=df['B'].astype(float)

My code looks like this. Will someone provide plausible solutions, please? Thank you all.

CodePudding user response:

Use boolean indexing.

E.g., something like:

df.loc[df['A'].notnull() & df['B'].notnull(), "Avg"] = (df['A'].astype(float)   df['B'].astype(float))/2

And similarly for the other conditions.

  • Related