Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
slicing dropna
#1
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
Reply
#2
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']
Reply
#3
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.
Reply
#4
Maybe they were dropping the quotes...
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Nu-B Q on dropna([list]) expat_th 0 1,196 May-31-2020, 02:43 AM
Last Post: expat_th
  Dropna Subset Not Working In Code eddywinch82 0 3,682 Mar-05-2020, 03:10 PM
Last Post: eddywinch82

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020