Data Scientist in Python (Step 3: Challenge: Cleaning Data, screen 5)

Screen Link:
https://app.dataquest.io/c/25/m/102/challenge%3A-cleaning-data/5/consolidating-deaths

My Code:

def clean_deaths(row):
    num_deaths = 0
    columns = ['Death1', 'Death2', 'Death3', 'Death4', 'Death5']
    
    for c in columns:
        death = row[c]
        if death.isnull() or death == 'NO':
            continue
        elif death == 'YES':
            num_deaths += 1
    return num_deaths

true_avengers['Deaths'] = true_avengers.apply(clean_deaths, axis=1)

Replace this line with your code

def clean_deaths(row):
    num_deaths = 0
    columns = ['Death1', 'Death2', 'Death3', 'Death4', 'Death5']
    
    for c in columns:
        death = row[c]
        if pd.isnull(death) or death == 'NO':
            continue
        elif death == 'YES':
            num_deaths += 1
    return num_deaths

true_avengers['Deaths'] = true_avengers.apply(clean_deaths, axis=1)

What I expected to happen:

What actually happened:

May I know why is there a difference between pd.isnull(death) and death.isnull()? When I used death.isnull(), the error below popped up but when I use pd.isnull(death), the code is perfectly fine.

AttributeError: ‘str’ object has no attribute 'isnull

2 Likes

The difference is because of what isnull() is being applied to.

When you use pd.isnull() you are using the isnull() method in Pandas and applying it to death. As per the documentation, death can be a scalar or array-like. In this case, death would be a string or float (for the NaN values). Those two fall under scalar so pd.isnull() works as expected.

However, when you use death.isnull() you are trying to use the isnull() method for the death object. As mentioned above, death is either a string or a float and neither of those has a isnull() method (it’s Pandas’ specific, I believe). So, you get an error.

An alternative that could work (I haven’t tested this) would be if death is None assuming death is only scalar (which I think it is in this case).

2 Likes

I see. Well understood. Thanks a lot!

1 Like