def get_n_last_observations_from_trajectories(trajectories, n, ascending=True):
    """
    Get n extremity observations from trajectories

    Parameters
    ----------
    trajectories : dataframe
        a dataframe with a trajectory_id column that identify trajectory observations. (column trajectory_id and jd have to be present)
    n : integer
        the number of extremity observations to return.
    ascending : boolean
        if set to True, return the most recent extremity observations, return the oldest ones otherwise, default to True.

    Returns
    -------
    last_trajectories_observations : dataframe
        the n last observations from the recorded trajectories

    Examples
    --------
    >>> from pandera import Check, Column, DataFrameSchema

    >>> test = pd.DataFrame({
    ... "candid" : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
    ... "jd" : [0.0, 1.0, 2, 3, 4, 5, 6, 7, 8, 9],
    ... "trajectory_id" : [1, 1, 1, 1, 2, 2, 3, 3, 3, 3]
    ... })

    >>> df_schema = DataFrameSchema({
    ... "jd": Column(float),
    ... "trajectory_id": Column(int)
    ... })

    >>> res = get_n_last_observations_from_trajectories(test, 1, False)

    >>> res = df_schema.validate(res).reset_index(drop=True)

    >>> df_expected = pd.DataFrame({
    ... "candid" : [6, 4, 0],
    ... "jd" : [6.0, 4.0, 0.0],
    ... "trajectory_id" : [3, 2, 1]
    ... })

    >>> assert_frame_equal(res, df_expected)

    >>> res = get_n_last_observations_from_trajectories(test, 1, True)

    >>> res = df_schema.validate(res).reset_index(drop=True)

    >>> df_expected = pd.DataFrame({
    ... "candid" : [3, 5, 9],
    ... "jd" : [3.0, 5.0, 9.0],
    ... "trajectory_id" : [1, 2, 3]
    ... })

    >>> assert_frame_equal(res, df_expected)

    >>> res = get_n_last_observations_from_trajectories(test, 2, True)

    >>> res = df_schema.validate(res).reset_index(drop=True)

    >>> df_expected = pd.DataFrame({
    ... "candid" : [2, 3, 4, 5, 8, 9],
    ... "jd" : [2.0, 3.0, 4.0, 5.0, 8.0, 9.0],
    ... "trajectory_id" : [1, 1, 2, 2, 3, 3]
    ... })

    >>> assert_frame_equal(res, df_expected)

    >>> res = get_n_last_observations_from_trajectories(test, 2, False)

    >>> res = df_schema.validate(res).reset_index(drop=True)

    >>> df_expected = pd.DataFrame({
    ... "candid" : [7, 6, 5, 4, 1, 0],
    ... "jd" : [7.0, 6.0, 5.0, 4.0, 1.0, 0.0],
    ... "trajectory_id" : [3, 3, 2, 2, 1, 1]
    ... })

    >>> assert_frame_equal(res, df_expected)
    """

    return (
        trajectories.sort_values(["jd"], ascending=ascending)
        .groupby(["trajectory_id"])
        .tail(n)
        .sort_values(["jd", "trajectory_id"], ascending=ascending)
    )