Built with Tutify.io

    AIStudyLabs

    Polars Filter DataFrame with Multilple Conditions

    Polars Filter DataFrame with Multilple Conditions

    The Polars filter() function is used to filter rows in a DataFrame based on one or more conditions. When you want to filter a DataFrame with multiple conditions, you can combine these conditions using logical operators like AND (&), OR (|), and NOT (~). This allows you to apply complex filters that can involve different columns and data types, including numerical, string, and date values. In this article, I will explain the polars filter DataFrame with multiple conditions.

    Key Points –

    <a id="h-usage-of-polars-filter-dataframe-with-multilple-conditions"></a>

    Usage of Polars Filter DataFrame with Multilple Conditions

    In Polars, filter DataFrame with multiple conditions allows you to retrieve rows that meet certain criteria. The filter method in Polars works with expressions that can combine conditions using logical operators such as & (AND), | (OR), and ~ (NOT).

    Now, let’s create a Polars DataFrame using data from a dictionary.

    
    import polars as pl
    
    # Creating a new Polars DataFrame
    technologies= {
        'Courses':["Spark","PySpark","Hadoop","Python","Pandas"],
        'Fees' :[22000,25000,20000,24000,26000],
        'Duration':['30days','50days','40days','50days','40days'],
        'Discount':[1000,2300,1500,1200,2500]
    }
    
    df = pl.DataFrame(technologies)
    print("Original DataFrame:\n", df)
    

    Yields below output.

    <a id="h-filter-rows-based-on-numerical-conditions"></a>

    Filter Rows Based on Numerical Conditions

    To filter rows based on numerical conditions in Polars, you can use the filter method with expressions that specify the desired conditions.

    
    # Filtering rows where Fees are greater than 23000
    filtered_df = df.filter(df["Fees"] > 23000)
    print("Filtered DataFrame:\n", filtered_df)
    

    Here,

    Alternatively, to filter rows where the Discount is greater than the average Discount in Polars, you can calculate the average discount using the .mean() function and then filter the DataFrame based on this condition.

    
    # Calculate the average discount
    avg_discount = df["Discount"].mean()
    
    # Filter rows where Discount is greater than the average
    filtered_df = df.filter(df["Discount"] > avg_discount)
    print("Filtered DataFrame:\n", filtered_df)
    
    # Output:
    # Filtered DataFrame:
    # shape: (2, 4)
    ┌─────────┬───────┬──────────┬──────────┐
    │ Courses ┆ Fees  ┆ Duration ┆ Discount │
    │ ---     ┆ ---   ┆ ---      ┆ ---      │
    │ str     ┆ i64   ┆ str      ┆ i64      │
    ╞═════════╪═══════╪══════════╪══════════╡
    │ PySpark ┆ 25000 ┆ 50days   ┆ 2300     │
    │ Pandas  ┆ 26000 ┆ 40days   ┆ 2500     │
    └─────────┴───────┴──────────┴──────────┘
    

    Here,

    <a id="h-filter-rows-with-a-string-condition"></a>

    Filter Rows with a String Condition

    To filter rows based on a string condition in Polars, you can use the filter method with expressions that evaluate string columns.

    
    # Filter rows where the course is "Python"
    filtered_df = df.filter(df["Courses"] == "Python")
    print("Filtered DataFrame:\n", filtered_df)
    
    # Output:
    # Filtered DataFrame:
    # shape: (1, 4)
    ┌─────────┬───────┬──────────┬──────────┐
    │ Courses ┆ Fees  ┆ Duration ┆ Discount │
    │ ---     ┆ ---   ┆ ---      ┆ ---      │
    │ str     ┆ i64   ┆ str      ┆ i64      │
    ╞═════════╪═══════╪══════════╪══════════╡
    │ Python  ┆ 24000 ┆ 50days   ┆ 1200     │
    └─────────┴───────┴──────────┴──────────┘
    

    Here,

    <a id="h-filter-using-logical-or"></a>

    Filter Using Logical OR

    To filter rows using logical OR in Polars, you can combine multiple conditions with the | operator. This allows you to select rows where at least one of the conditions is true.

    
    # Filter rows where Fees are greater than 24000 OR Course is "Python"
    filtered_df = df.filter((df["Fees"] > 24000) | (df["Courses"] == "Python"))
    print("Filtered DataFrame:\n", filtered_df)
    
    # Output:
    # Filtered DataFrame:
    # shape: (3, 4)
    ┌─────────┬───────┬──────────┬──────────┐
    │ Courses ┆ Fees  ┆ Duration ┆ Discount │
    │ ---     ┆ ---   ┆ ---      ┆ ---      │
    │ str     ┆ i64   ┆ str      ┆ i64      │
    ╞═════════╪═══════╪══════════╪══════════╡
    │ PySpark ┆ 25000 ┆ 50days   ┆ 2300     │
    │ Python  ┆ 24000 ┆ 50days   ┆ 1200     │
    │ Pandas  ┆ 26000 ┆ 40days   ┆ 2500     │
    └─────────┴───────┴──────────┴──────────┘
    

    Here,

    <a id="h-filter-with-negation-not"></a>

    Filter with Negation (NOT)

    To filter rows where a column does not match a specific value, you can use the negation operator (~) in combination with the equality condition. This will allow you to exclude rows that match the given value, retaining only those that don't match.

    
    # Filter where the course is NOT "Python"
    filtered_df = df.filter(~(df["Courses"] == "Python"))
    print("Filtered DataFrame:\n", filtered_df)
    
    # Output:
    # Filtered DataFrame:
    # shape: (4, 4)
    ┌─────────┬───────┬──────────┬──────────┐
    │ Courses ┆ Fees  ┆ Duration ┆ Discount │
    │ ---     ┆ ---   ┆ ---      ┆ ---      │
    │ str     ┆ i64   ┆ str      ┆ i64      │
    ╞═════════╪═══════╪══════════╪══════════╡
    │ Spark   ┆ 22000 ┆ 30days   ┆ 1000     │
    │ PySpark ┆ 25000 ┆ 50days   ┆ 2300     │
    │ Hadoop  ┆ 20000 ┆ 40days   ┆ 1500     │
    │ Pandas  ┆ 26000 ┆ 40days   ┆ 2500     │
    └─────────┴───────┴──────────┴──────────┘
    

    <a id="h-filter-with-date-conditions"></a>

    Filter with Date Conditions

    You can filter rows based on date conditions in Polars by using expressions that compare date columns with specific date values. Polars supports operations like ==, >, <, >=, and <= for filtering DataFrames based on dates.

    
    import polars as pl
    from datetime import date
    
    # Creating a Polars DataFrame with a Date column
    data = {
        'Courses': ["Spark", "PySpark", "Hadoop", "Python", "Pandas"],
        'Start_Date': [date(2024, 1, 15), date(2024, 5, 20), date(2024, 3, 10), date(2024, 7, 5), date(2024, 4, 18)],
        'Fees': [22000, 25000, 20000, 24000, 26000],
        'Duration': ['30days', '50days', '40days', '50days', '40days'],
        'Discount': [1000, 2300, 1500, 1200, 2500]
    }
    
    df = pl.DataFrame(data)
    
    # Filter rows where the Start_Date is after January 1, 2024
    filtered_df = df.filter(df["Start_Date"] > date(2024, 1, 15))
    print("Filtered DataFrame:\n", filtered_df)
    
    # Output:
    # Filtered DataFrame:
    # shape: (4, 5)
    ┌─────────┬────────────┬───────┬──────────┬──────────┐
    │ Courses ┆ Start_Date ┆ Fees  ┆ Duration ┆ Discount │
    │ ---     ┆ ---        ┆ ---   ┆ ---      ┆ ---      │
    │ str     ┆ date       ┆ i64   ┆ str      ┆ i64      │
    ╞═════════╪════════════╪═══════╪══════════╪══════════╡
    │ PySpark ┆ 2024-05-20 ┆ 25000 ┆ 50days   ┆ 2300     │
    │ Hadoop  ┆ 2024-03-10 ┆ 20000 ┆ 40days   ┆ 1500     │
    │ Python  ┆ 2024-07-05 ┆ 24000 ┆ 50days   ┆ 1200     │
    │ Pandas  ┆ 2024-04-18 ┆ 26000 ┆ 40days   ┆ 2500     │
    └─────────┴────────────┴───────┴──────────┴──────────┘
    

    Here,

    <a id="h-filter-with-multiple-conditions-across-data-types"></a>

    Filter with Multiple Conditions Across Data Types

    Similarly, you can filter rows with multiple conditions across different data types by combining conditions that apply to different columns in Polars. You can filter based on numerical, string, or date columns, and combine these conditions using logical operators like AND (&), OR (|), and NOT (~).

    
    # Filter rows where:
    # Fees are greater than 22000
    # The course is "Python" or "Pandas"
    # Start date is after March 1, 2023
    filtered_df = df.filter(
        (df["Fees"] > 22000) &
        (df["Courses"].is_in(["Python", "Pandas"])) &
        (df["Start_Date"] > date(2024, 3, 1))
    )
    print("Filtered DataFrame:\n", filtered_df)
    
    # Output:
    # Filtered DataFrame:
    # shape: (2, 5)
    ┌─────────┬────────────┬───────┬──────────┬──────────┐
    │ Courses ┆ Start_Date ┆ Fees  ┆ Duration ┆ Discount │
    │ ---     ┆ ---        ┆ ---   ┆ ---      ┆ ---      │
    │ str     ┆ date       ┆ i64   ┆ str      ┆ i64      │
    ╞═════════╪════════════╪═══════╪══════════╪══════════╡
    │ Python  ┆ 2024-07-05 ┆ 24000 ┆ 50days   ┆ 1200     │
    │ Pandas  ┆ 2024-04-18 ┆ 26000 ┆ 40days   ┆ 2500     │
    └─────────┴────────────┴───────┴──────────┴──────────┘
    

    Here,

    <a id="h-conclusion"></a>

    Conclusion

    In conclusion, filtering a Polars DataFrame with multiple conditions provides a powerful approach to extract rows based on intricate criteria across different column types, including numerical, string, and date values. By using logical operators like AND (&), OR (|), and NOT (~), you can combine multiple conditions in a flexible and efficient way.

    Happy Learning!!

    <a id="h-related-articles"></a>

    Related Articles

    <a id="h-reference"></a>

    Reference