Python Forum

Full Version: slicing dropna
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi Gurus,

I am doing python course on datacamp and I have come across the below exercise.
def check_null_or_valid(row_data):
    """Function that takes a row of data,
    drops all missing values,
    and checks if all remaining values are greater than or equal to 0
    """
    no_na = row_data.dropna()[1:-1]
    numeric = pd.to_numeric(no_na)
    ge0 = numeric >= 0
    return ge0

# Check whether the first column is 'Life expectancy'
assert g1800s.columns[0] == 'Life expectancy'

# Check whether the values in the row are valid
assert g1800s.iloc[:, 1:].apply(check_null_or_valid, axis=1).all().all()

# Check that there is only one instance of each country
assert g1800s['Life expectancy'].value_counts()[0] == 1
I would like to know what the following step does:
row_data.dropna()[1:-1]
TIA
dropna()
Drop the rows where at least one element is missing.

[1:-1] is Python slice notation,it will remove first and last value in a list.
Here how it work on list,try without and see what it dos to DataFrame row_data.
>>> lst = list('hello')
>>> lst
['h', 'e', 'l', 'l', 'o']

>>> lst[1:-1]
['e', 'l', 'l']

>>> lst[3:]
['l', 'o']

>>> lst[1:-2]
['e', 'l']

>>> lst[::-1]
['o', 'l', 'l', 'e', 'h']
Thanks Mate.
I did understand them separately but looking at the requirement("Function that takes a row of data,
drops all missing values") I wasn't sure why they used it together.
Maybe they were dropping the quotes...