Getting Familiar With lambda Functions
Sometimes we need to put some conditions on the indices. In these cases, you need to use a lambda
function inside iloc[]
.
Let's figure out what we can do using lambda
:
pythondata.iloc[lambda x: x.index < 5]
This code will output the first five rows of the dataset, the rows with the indices 0
, 1
, 2
, 3
, and 4
.
lambda x
-x
is the argument we will work with (the item of the data set);x.index
- extracts only values of rows' indices;x.index < 5
- the condition according to which we will extract data. Here, only rows with indices that are less than5
.
Swipe to start coding
Your task here is to divide data into two groups: one has odd indices and the other even. Follow the algorithm:
- Import the
pandas
library with thepd
alias. - Read the csv file.
- Extract only rows with even indices:
- Apply the
.iloc[]
attribute to thedata
; - Within the
.iloc[]
attribute, apply thelambda
function with thex
argument; - Set a condition to check if the number is even (if you do not know how to do this, check the hint).
- Apply the
- Extract only rows with odd indices:
- Apply the
.iloc[]
attribute to thedata
; - Within the
.iloc[]
attribute, apply thelambda
function with thex
argument; - Set a condition to check if the number is odd (if you do not know how to do this, check the hint).
- Apply the
- Output data:
- Output the first five rows of the
even
indices; - Output the last five rows of the
odd
indices.
- Output the first five rows of the
Solution
Thanks for your feedback!