Built with Tutify.io

    AIStudyLabs

    Polars Series tail() Usage & Examples

    Polars Series tail() Usage & Examples

    In Polars, the tail() function is used to retrieve the last n rows of a Series, similar to its counterpart in Pandas. By default, it returns the last ten elements, but you can specify a different number of elements if needed. This function is useful for inspecting recent data, particularly when working with large datasets or when you prefer to quickly view the "tail end" of the data instead of the beginning.

    In this article, I will explain the tail() function in Polars Series, covering its syntax, parameters, usage, and how to create a new Polars series containing the last n rows from the original Series.

    Key Points –

    <a id="h-polars-series-tail-introduction"></a>

    Polars Series tail() Introduction

    Let’s know the syntax of the series tail() method.

    
    # Syntax of tail()
    Series.tail(n: int = 10) → Series
    

    <a id="h-parameters-of-the-series-tail"></a>

    Parameters of the Series tail()

    It allows only one parameter.

    <a id="h-return-value"></a>

    Return Value

    This function returns a new Series containing the last n elements from the original Series.

    <a id="h-usage-of-polars-series-tail-method"></a>

    Usage of Polars Series tail() Method

    The tail() method returns the last N elements of a Polars Series. It's useful when you need to view the most recent entries of a dataset, particularly for time-series data or when analyzing the end of a dataset.

    First, let’s create a Polars Series.

    
    import polars as pl
    
    # Sample Series
    ser = pl.Series("values", [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60])
    print("Original Series:\n", ser)
    

    Yields below output.

    To return the last 10 rows of the series using the tail() method in Polars (which is the default behavior), you can simply call the tail() method without passing any argument.

    
    # Get the last 10 elements (default behavior)
    result = ser.tail()
    print("Last 10 elements:\n", result)
    

    In the above example, the tail() method is used to retrieve the last 10 elements from the Series, which are [15, 20, 25, 30, 35, 40, 45, 50, 55, 60]. Since tail() by default fetches the last 10 elements if no argument is passed, this is a typical use case for inspecting the end of a dataset.

    <a id="h-using-tail-to-retrieve-the-last-3-elements-from-a-series"></a>

    Using tail() to Retrieve the Last 3 Elements from a Series

    You can use the tail() method to retrieve the last 3 elements of a polars Series. This method returns a new Series containing the last n values from the original one. It's a handy way to quickly access the most recent entries in your data.

    
    # Get the last 3 elements
    result = ser.tail(3)
    print("Last 3 elements:\n", result)
    
    # Output:
    # Last 3 elements:
    # shape: (3,)
    # Series: 'values' [i64]
    # [
    #	50
    #	55
    #	60
    # ]
    

    In the above example, ser.tail(3) will return the last 3 elements from the Series, which are [50, 55, 60]. If you don't specify a number, it defaults to 10, returning the last 10 elements.

    <a id="h-using-tail-on-time-series-data"></a>

    Using tail() on Time-Series Data

    When working with time-series data, you often want to quickly peek at the most recent records, like the last few days, hours, or seconds of observations. This is where the tail() method comes in handy.

    
    import polars as pl
    from datetime import datetime, timedelta
    
    # Create a time-series Series
    dates = [datetime(2025, 1, 1) + timedelta(days=i) for i in range(10)]
    ser = pl.Series("dates", dates)
    print("Last 3 dates:\n", ser.tail(3))
    
    # Output:
    # Last 3 dates:
    # shape: (3,)
    # Series: 'dates' [datetime[μs]]
    # [
    #	2025-01-08 00:00:00
    #	2025-01-09 00:00:00
    #	2025-01-10 00:00:00
    # ]
    

    <a id="h-using-tail-with-negative-numbers"></a>

    Using tail() with Negative Numbers

    When you use tail(-n), it returns all rows except the first n rows from the polars Series. This is different from typical usage where tail(n) gives you the last n rows. The negative value flips the logic.

    
    import polars as pl
    
    # Sample Series
    ser = pl.Series("values", [5, 10, 15, 20, 25, 30, 35])
    
    # Use tail with a negative number
    print("tail(-3):\n", ser.tail(-3))
    
    # Output:
    # tail(-3):
    # shape: (4,)
    # Series: 'values' [i64]
    # [
    #	20
    #	25
    #	30
    #	35
    # ]
    

    Polars expects the argument to tail() to be a non-negative integer representing how many elements to return from the end of the Series. Unlike some other contexts where a negative value might mean "drop the first n" or similar, Polars enforces strict input validation here.

    <a id="h-using-tail-on-a-large-dataset"></a>

    Using tail() on a Large Dataset

    When working with large datasets, the tail() method can be extremely useful for efficiently viewing the last few rows without having to load or print the entire dataset. This is particularly beneficial for exploratory data analysis (EDA), debugging, or simply inspecting recent data entries in time-series or log data.

    
    import polars as pl
    import numpy as np
    
    # Create a large dataset with 1 million rows
    large_data = np.random.randint(0, 100, size=1000000)
    ser = pl.Series("values", large_data)
    
    # Get the last 5 elements
    result = ser.tail(5)
    print("Last 5 elements:\n", result)
    
    # Output:
    # Last 5 elements:
    # shape: (5,)
    # Series: 'values' [i32]
    # [
    #	95
    #	60
    #	25
    #	53
    #	17
    # ]
    

    <a id="h-combining-tail-with-aggregation"></a>

    Combining tail() with Aggregation

    When working with large datasets or time-series data, you often need to perform aggregation operations on a specific subset of data, such as the last few rows. Combining the tail() method with aggregation functions in Polars allows you to extract and summarize the final elements of your data efficiently.

    <a id="h-summing-the-last-n-elements"></a>

    Summing the Last n Elements

    You can combine tail() with an aggregation function like sum() to compute the sum of the last n rows.

    
    import polars as pl
    
    # Sample data
    ser = pl.Series("values", [5, 10, 15, 20, 25, 30, 35])
    
    # Get the last 4 elements and calculate their sum
    result = ser.tail(4).sum()
    print(result)  
    
    # Output:
    # 110
    

    <a id="h-calculating-the-mean-of-the-last-n-rows"></a>

    Calculating the Mean of the Last n Rows

    The mean() function can be combined with tail() to calculate the average of the last n values.

    
    # Calculating the mean of the last n rows
    result = ser.tail(3).mean()
    print(result)
    
    # Output:
    # 30.0
    

    <a id="h-counting-non-null-values-in-the-last-n-rows"></a>

    Counting Non-Null Values in the Last n Rows

    You can use count() to count non-null values in the last few elements of a Series.

    
    import polars as pl
    
    ser_with_nulls = pl.Series("values", [5, None, 15, None, 25, 30, 35])
    
    result = ser_with_nulls.tail(5).count()
    print(result) 
    
    # Output:
    # 4
    

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

    Conclusion

    In Conclusion, the tail() method in Polars is a straightforward and powerful way to retrieve the last n elements from a Series. It is particularly useful when you are working with datasets where you are interested in inspecting the most recent or last entries, such as with time-series data or streaming datasets.

    Happy Learning!!

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

    Related Articles

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

    Reference