Is there a head and tail method for Numpy array?

PythonNumpy

Python Problem Overview


I loaded a csv file into 'dataset' and tried to execute dataset.head(), but it reports an error. How to check the head or tail of a numpy array? without specifying specific lines?

Python Solutions


Solution 1 - Python

For a head-like function you can just slice the array using dataset[:10].

For a tail-like function you can just slice the array using dataset[-10:].

Solution 2 - Python

You can do this for any python iterable.

PEP-3132 which is in python 3.x (https://www.python.org/dev/peps/pep-3132/) can use the * symbol for the 'rest' of the iterable.

To do what you want:

>>> import numpy as np
>>> np.array((1,2,3))
array([1, 2, 3])
>>> head, *tail = np.array((1,2,3))
>>> head
1
>>> tail
[2, 3]

Solution 3 - Python

This works well:

def nparray_tail(x: np.array, n:int):
    """
    Returns tail N elements of array.
    :param x: Numpy array.
    :param n: N elements to return on end.
    :return: Last N elements of array.
    """
    if n == 0:
        return x[0:0]  # Corner case: x[-0:] will return the entire array but tail(0) should return an empty array.
    else:
        return x[-n:]  # Normal case: last N elements of array.

Discussion

As a bonus, this fixes a non-intuitive corner case in the answer from @feedMe: dataset[-0:] returns the entire array, not an empty array as one would expect when requesting the last 0 elements on the tail end of the array. This is consistent with the .tail() function in Pandas.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlingView Question on Stackoverflow
Solution 1 - PythonfeedMeView Answer on Stackoverflow
Solution 2 - PythonOliver DudgeonView Answer on Stackoverflow
Solution 3 - PythonContangoView Answer on Stackoverflow