Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Filtering Rows with lambda Functions | Getting Familiar With Indexing and Selecting Data
Data Wrangling with pandas
Section 1. Chapter 6
single

single

bookFiltering 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:

  1. Import the pandas library with the pd alias.
  2. Read the csv file.
  3. Extract only rows with even indices:
    • Apply the .iloc[] attribute to the data;
    • Within the .iloc[] attribute, apply the lambda function with the x argument;
    • Set a condition to check if the number is even (if you do not know how to do this, check the hint).
  4. Extract only rows with odd indices:
    • Apply the .iloc[] attribute to the data;
    • Within the .iloc[] attribute, apply the lambda function with the x argument;
    • Set a condition to check if the number is odd (if you do not know how to do this, check the hint).
  5. Output data:
    • Output the first five rows of the even indices;
    • Output the last five rows of the odd indices.

Solution

Note
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
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.

Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 1. Chapter 6
single

single

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

some-alt