Monday, 18 December 2023

Pandas: Filter rows of a DataFrame using where method

Using ‘where()’ method, we can filter the rows of a DataFrame.

I am using below data set to demonstrate the examples.

       Name  Age       City  Gender  Rating
0   Krishna   34  Bangalore    Male      39
1     Sailu   35  Hyderabad  Female      43
2      Joel   29  Hyderabad    Male      67
3     Chamu   35    Chennai  Female     100
4  Jitendra   52  Bangalore    Male      41
5       Raj   34    Chennai    Male      89

Example 1: Get all the users who are from the city 'Bangalore'

bangalore_users = df.where(df['City'] == 'Bangalore')

‘bangalore_users’ point to the below data set.

        Name   Age       City Gender  Rating
0   Krishna  34.0  Bangalore   Male    39.0
1       NaN   NaN        NaN    NaN     NaN
2       NaN   NaN        NaN    NaN     NaN
3       NaN   NaN        NaN    NaN     NaN
4  Jitendra  52.0  Bangalore   Male    41.0
5       NaN   NaN        NaN    NaN     NaN

As you see above output, ‘bangalore_users’ contains NaN values for rows where the condition is not met, and it retains the original values where the condition is met.

 

You can also provide an alternative value to replace the NaN values by passing  the second argument to the where() method.

 

For example,

bangalore_users = df.where(df['City'] == 'Bangalore', 'not_matched')

In the above example, ‘bangalore_users’ point to below data set.

           Name          Age         City       Gender       Rating
0      Krishna           34    Bangalore         Male           39
1  not_matched  not_matched  not_matched  not_matched  not_matched
2  not_matched  not_matched  not_matched  not_matched  not_matched
3  not_matched  not_matched  not_matched  not_matched  not_matched
4     Jitendra           52    Bangalore         Male           41
5  not_matched  not_matched  not_matched  not_matched  not_matched

In this case, the rows that don't meet the condition are replaced with the string 'not_matched' in the resulting DataFrame.

 

Example 2: Get the rows whose age is 34 or Gender is 'Female'

users_age_is_34_or_female = df.where((df['Age'] == 34) | (df['Gender'] == 'Female'), 'not_matched')

 

'users_age_is_34_or_female' will point to below data set.

           Name          Age         City       Gender       Rating
0      Krishna           34    Bangalore         Male           39
1        Sailu           35    Hyderabad       Female           43
2  not_matched  not_matched  not_matched  not_matched  not_matched
3        Chamu           35      Chennai       Female          100
4  not_matched  not_matched  not_matched  not_matched  not_matched
5          Raj           34      Chennai         Male           89

Find the below working application.

 

where_method.py

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Sailu', 'Joel', 'Chamu', 'Jitendra', "Raj"],
        'Age': [34, 35, 29, 35, 52, 34],
        'City': ['Bangalore', 'Hyderabad', 'Hyderabad', 'Chennai', 'Bangalore', 'Chennai'],
        'Gender': ['Male', 'Female', 'Male', 'Female', 'Male', 'Male'],
        'Rating': [39, 43, 67, 100, 41, 89]}
df = pd.DataFrame(data)
print('Original DataFrame')
print(df)

# Get the rows whose city is 'Bangalore'
bangalore_users = df.where(df['City'] == 'Bangalore')
print('\nbangalore_users\n', bangalore_users)

bangalore_users = df.where(df['City'] == 'Bangalore', 'not_matched')
print('\nbangalore_users\n', bangalore_users)

# Get the rows whose age is 34 or Gender is 'Female'
users_age_is_34_or_female = df.where((df['Age'] == 34) | (df['Gender'] == 'Female'), 'not_matched')
print('\nusers_age_is_35_or_female\n', users_age_is_34_or_female)

Output

Original DataFrame
       Name  Age       City  Gender  Rating
0   Krishna   34  Bangalore    Male      39
1     Sailu   35  Hyderabad  Female      43
2      Joel   29  Hyderabad    Male      67
3     Chamu   35    Chennai  Female     100
4  Jitendra   52  Bangalore    Male      41
5       Raj   34    Chennai    Male      89

bangalore_users
        Name   Age       City Gender  Rating
0   Krishna  34.0  Bangalore   Male    39.0
1       NaN   NaN        NaN    NaN     NaN
2       NaN   NaN        NaN    NaN     NaN
3       NaN   NaN        NaN    NaN     NaN
4  Jitendra  52.0  Bangalore   Male    41.0
5       NaN   NaN        NaN    NaN     NaN

bangalore_users
           Name          Age         City       Gender       Rating
0      Krishna           34    Bangalore         Male           39
1  not_matched  not_matched  not_matched  not_matched  not_matched
2  not_matched  not_matched  not_matched  not_matched  not_matched
3  not_matched  not_matched  not_matched  not_matched  not_matched
4     Jitendra           52    Bangalore         Male           41
5  not_matched  not_matched  not_matched  not_matched  not_matched

users_age_is_35_or_female
           Name          Age         City       Gender       Rating
0      Krishna           34    Bangalore         Male           39
1        Sailu           35    Hyderabad       Female           43
2  not_matched  not_matched  not_matched  not_matched  not_matched
3        Chamu           35      Chennai       Female          100
4  not_matched  not_matched  not_matched  not_matched  not_matched
5          Raj           34      Chennai         Male           89

 

Previous                                                 Next                                                 Home

Pandas: nlargest: Get n largest values in a DataFrame

Using ‘nlargest’ method, we can get n largest values in a DataFrame.

 

I am going to use below data set to demonstrate the examples.

       Name  Age       City  Gender  Rating
0   Krishna   34  Bangalore    Male      91
1     Sailu   35  Hyderabad  Female      76
2      Joel   29  Hyderabad    Male      67
3     Chamu   35    Chennai  Female     100
4  Jitendra   52  Bangalore    Male      87
5       Raj   34    Chennai    Male      89

 

Example 1: Get the three oldest people from the dataset.

three_oldest_emps = df.nlargest(3, columns='Age')

‘three_oldest_emps’ point to below data set.

        Name  Age       City  Gender  Rating
4  Jitendra   52  Bangalore    Male      87
1     Sailu   35  Hyderabad  Female      76
3     Chamu   35    Chennai  Female     100

Example 2: get the three oldest people by their rating from the dataset.

three_oldest_emps_by_rating = df.nlargest(3, columns=['Age', 'Rating'])

‘three_oldest_emps_by_rating’ point to below data set.

        Name  Age       City  Gender  Rating
4  Jitendra   52  Bangalore    Male      87
3     Chamu   35    Chennai  Female     100
1     Sailu   35  Hyderabad  Female      76

Find the below working application.

 

n_largest_rows.py

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Sailu', 'Joel', 'Chamu', 'Jitendra', "Raj"],
        'Age': [34, 35, 29, 35, 52, 34],
        'City': ['Bangalore', 'Hyderabad', 'Hyderabad', 'Chennai', 'Bangalore', 'Chennai'],
        'Gender': ['Male', 'Female', 'Male', 'Female', 'Male', 'Male'],
        'Rating': [91, 76, 67, 100, 87, 89]}

df = pd.DataFrame(data)
print('Original DataFrame')
print(df)

three_oldest_emps = df.nlargest(3, columns='Age')
print('\nthree_oldest_emps : \n', three_oldest_emps)

three_oldest_emps_by_rating = df.nlargest(3, columns=['Age', 'Rating'])
print('\nthree_oldest_emps_by_rating : \n', three_oldest_emps_by_rating)

Output

Original DataFrame
       Name  Age       City  Gender  Rating
0   Krishna   34  Bangalore    Male      91
1     Sailu   35  Hyderabad  Female      76
2      Joel   29  Hyderabad    Male      67
3     Chamu   35    Chennai  Female     100
4  Jitendra   52  Bangalore    Male      87
5       Raj   34    Chennai    Male      89

three_oldest_emps : 
        Name  Age       City  Gender  Rating
4  Jitendra   52  Bangalore    Male      87
1     Sailu   35  Hyderabad  Female      76
3     Chamu   35    Chennai  Female     100

three_oldest_emps_by_rating : 
        Name  Age       City  Gender  Rating
4  Jitendra   52  Bangalore    Male      87
3     Chamu   35    Chennai  Female     100
1     Sailu   35  Hyderabad  Female      76

 

Previous                                                 Next                                                 Home

Pandas: nsmallest: Get n smallest values in a DataFrame

Using ‘nsmallest’ method, we can get n smallest values in a DataFrame.

I am going to use below data set to demonstrate the examples.

       Name  Age       City  Gender  Rating
0   Krishna   34  Bangalore    Male      91
1     Sailu   35  Hyderabad  Female      76
2      Joel   29  Hyderabad    Male      67
3     Chamu   35    Chennai  Female     100
4  Jitendra   52  Bangalore    Male      87
5       Raj   34    Chennai    Male      89

 

Example 1: Get the three youngest employees.

three_younger_emps = df.nsmallest(3, columns='Age')

 

‘three_younger_emps’ point to below data set.

       Name  Age       City Gender  Rating
2     Joel   29  Hyderabad   Male      67
0  Krishna   34  Bangalore   Male      91
5      Raj   34    Chennai   Male      89

Example 2: Get three youngest employees by their rating also.

three_younger_emps_by_rating = df.nsmallest(3, columns=['Age', 'Rating'])

‘three_younger_emps_by_rating’ point to below data set.

       Name  Age       City Gender  Rating
2     Joel   29  Hyderabad   Male      67
5      Raj   34    Chennai   Male      89
0  Krishna   34  Bangalore   Male      91

Find the below working application.

 

n_smallest_rows.py

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Sailu', 'Joel', 'Chamu', 'Jitendra', "Raj"],
        'Age': [34, 35, 29, 35, 52, 34],
        'City': ['Bangalore', 'Hyderabad', 'Hyderabad', 'Chennai', 'Bangalore', 'Chennai'],
        'Gender': ['Male', 'Female', 'Male', 'Female', 'Male', 'Male'],
        'Rating': [91, 76, 67, 100, 87, 89]}

df = pd.DataFrame(data)
print('Original DataFrame')
print(df)

three_younger_emps = df.nsmallest(3, columns='Age')
print('\nthree_younger_emps : \n', three_younger_emps)

three_younger_emps_by_rating = df.nsmallest(3, columns=['Age', 'Rating'])
print('\nthree_younger_emps_by_rating : \n', three_younger_emps_by_rating)

Output

Original DataFrame
       Name  Age       City  Gender  Rating
0   Krishna   34  Bangalore    Male      91
1     Sailu   35  Hyderabad  Female      76
2      Joel   29  Hyderabad    Male      67
3     Chamu   35    Chennai  Female     100
4  Jitendra   52  Bangalore    Male      87
5       Raj   34    Chennai    Male      89

three_younger_emps : 
       Name  Age       City Gender  Rating
2     Joel   29  Hyderabad   Male      67
0  Krishna   34  Bangalore   Male      91
5      Raj   34    Chennai   Male      89

three_younger_emps_by_rating : 
       Name  Age       City Gender  Rating
2     Joel   29  Hyderabad   Male      67
5      Raj   34    Chennai   Male      89
0  Krishna   34  Bangalore   Male      91



Previous                                                 Next                                                 Home

Ensuring Platform-Independent Accuracy: A Guide to strictfp in Java

Expressing floating-point numbers in binary format introduces rounding errors, and the extent of these errors can differ based on the hardware and operating system, resulting in discrepancies in calculations across different platforms.

 

By default, the operation on floating point numbers are platform dependent. This can lead to unexpected results when running the same code on different platforms.

 

To mitigate this issue, we can use strictfp (strict floating-point) keyword which ensures uniform and predictable floating-point calculations across varied platforms. When a class, interface, or method is annotated with the strictfp modifier, it signifies that all floating-point calculations within that context must conform to the IEEE 754 standard for floating-point arithmetic.

 

In Java, the platform's native floating-point implementation is employed by default, and this may vary across distinct hardware and operating systems. The strictfp modifier serves to standardize floating-point calculations, particularly in scenarios where consistent cross-platform precision is imperative, such as in scientific or financial applications.

 

What is IEEE 754 standard?

The IEEE 754 standard, formally known as the "Standard for Floating-Point Arithmetic," is a technical specification outlining the representation and manipulation of real numbers in binary computing. Embraced by hardware and software across diverse platforms, it stands as the prevailing standard for conducting floating-point operations in modern computing systems.

 

Applying strictfp to a class

When strictfp is applied to a class or interface, all methods within that class or interface, including nested classes, adhere to strict floating-point rules.


 

public strictfp class ArithmeticUtil {

  public static float add(float f1, float f2) {
    return f1 + f2;
  }

  public static float sub(float f1, float f2) {
    return f1 - f2;
  }

  public static float mul(float f1, float f2) {
    return f1 * f2;
  }

  public static float div(float f1, float f2) {
    return f1 / f2;
  }
}

 

Applying strictfp to a method

When strictfp is applied to a method, it ensures that all floating-point calculations within that specific method follow strict floating-point rules.

public class App {

  public strictfp float areaOfCircle(float radius) {
    return 3.14f * radius * radius;
  }

}

 

Consider employing strictfp in the following scenarios:

a. Financial calculations

Precision and consistency are paramount in financial applications such as banking and investments.

 

b. Scientific and engineering applications

Accurate floating-point calculations are vital for scientific simulations and engineering computations.

 

c. Code ported across platforms

When aiming for consistent performance across diverse architectures, the use of strictfp proves valuable.

 

Note

a. Use of strictfp may introduce a performance impact due to the imposition of more rigorous rules on floating-point calculations. For typical programming scenarios, the default floating-point behaviour generally suffecient, rendering strictfp unnecessary. Nevertheless, in situations demanding precise and consistent floating-point calculations across diverse platforms, the adoption of strictfp can be advantageous.

 

b. Despite enhancing portability and consistency, it's essential to acknowledge that strictfp does not completely eliminate all platform-dependent issues. Some variations in hardware and software may still influence particular calculations.

 

 

 

You may like

Interview Questions

Design an utility class to capture application metrics summary in Java

Utility class to get primitive type from wrapper type and vice versa

FNV hash algorithm implementation in Java

Controlling Randomness in Java: Exploring the Role of Seeds in java.util.Random

Calculating initial capacity from expected size and load factor

A Beginner's Guide to UUID Types