Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele Learning About lambda Functions | Tutustuminen Indeksointiin ja Datan Valintaan
Harjoittele
Projektit
Tietovisat & Haasteet
Visat
Haasteet
/
Datan Käsittely Pandas-Kirjastolla

bookLearning About lambda Functions

Pyyhkäise näyttääksesi valikon

Note
Definition

A lambda function is a small, anonymous function defined with the lambda keyword. Unlike regular functions defined with def, a lambda function has no name and is meant for short, one-time-use logic.

The syntax is:

lambda arguments: expression

The function takes arguments and returns the result of expression. A few simple examples:

12345
double = lambda x: x * 2 print(double(5)) # Returns 10 is_even = lambda x: x % 2 == 0 print(is_even(4)) # Returns True
copy

Using lambda with iloc[]

In pandas, iloc[] normally accepts integer-based positions. However, you can also pass a lambda function – in this case, x refers to the DataFrame itself, and x.index gives you the row index values:

data.iloc[lambda x: x.index < 5]

This returns the first five rows (indices 0 through 4). Here is what each part does:

  • lambda x: defines an anonymous function where x is the DataFrame;
  • x.index: accesses the row index values;
  • x.index < 5: the filtering condition; only rows whose index is less than 5 are selected.

The result is a boolean array that iloc[] uses to filter rows.

Filtering by Index Parity

A common use case is splitting a dataset by even and odd indices. The modulo operator % returns the remainder of division:

123456789101112
import pandas as pd # Data import data = pd.read_csv('https://codefinity-content-media.s3.eu-west-1.amazonaws.com/4bf24830-59ba-4418-969b-aaf8117d522e/IMDb_Data_final.csv') # Rows with even indices (0, 2, 4, ...) even = data.iloc[lambda x: x.index % 2 == 0] print(even.head()) # Rows with odd indices (1, 3, 5, ...) odd = data.iloc[lambda x: x.index % 2 != 0] print(odd.head())
copy

x.index % 2 == 0 is True when the index is divisible by 2 (even), and False otherwise.

question mark

What does x refer to in the following code?

Valitse oikea vastaus

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 1. Luku 5

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

Osio 1. Luku 5
some-alt