Section 1. Chapter 6
single
Filtering Rows with lambda Functions
Swipe to show menu
Task
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
pandaslibrary with thepdalias. - Read the csv file.
- Extract only rows with even indices:
- Apply the
.iloc[]attribute to thedata; - Within the
.iloc[]attribute, apply thelambdafunction with thexargument; - 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 thelambdafunction with thexargument; - 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
evenindices; - Output the last five rows of the
oddindices.
- Output the first five rows of the
Solution
Note
To check if an index is even or odd, use the % (modulo) operator – it returns the remainder of a division. If x.index % 2 == 0, the remainder is 0, meaning the index is even. If x.index % 2 != 0, the remainder is 1, meaning the index is odd.
Note
To display only the first or last rows of a DataFrame, use the .head(n) and .tail(n) methods, where n is the number of rows to display. By default, both methods return 5 rows if n is not specified.
Everything was clear?
Thanks for your feedback!
Section 1. Chapter 6
single
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat