Home >Backend Development >Python Tutorial >How Can I Efficiently Justify a NumPy Array's Non-Zero Elements?

How Can I Efficiently Justify a NumPy Array's Non-Zero Elements?

DDD
DDDOriginal
2024-12-08 05:23:11916browse

How Can I Efficiently Justify a NumPy Array's Non-Zero Elements?

Justifying non-zero elements to a particular side (often useful in searches) is a common operation, which can be done directly for a NumPy array. Here's how -

import numpy as np

def justify(a, invalid_val=0, axis=1, side='left'):    
    """
    Justifies a 2D array

    Parameters
    ----------
    A : ndarray
        Input array to be justified
    axis : int
        Axis along which justification is to be made
    side : str
        Direction of justification. It could be 'left', 'right', 'up', 'down'
        It should be 'left' or 'right' for axis=1 and 'up' or 'down' for axis=0.

    """

    if invalid_val is np.nan:
        mask = ~np.isnan(a)
    else:
        mask = a!=invalid_val
    justified_mask = np.sort(mask,axis=axis)
    if (side=='up') | (side=='left'):
        justified_mask = np.flip(justified_mask,axis=axis)
    out = np.full(a.shape, invalid_val) 
    if axis==1:
        out[justified_mask] = a[mask]
    else:
        out.T[justified_mask.T] = a.T[mask.T]
    return out

The snippet above can justify a 2D array along a chosen axis in any of the four possible directions -

# sample input array
a = np.array([[1, 0, 2, 0], 
              [3, 0, 4, 0], 
              [5, 0, 6, 0], 
              [0, 7, 0, 8]])

# shift to left
print(justify(a, axis=0, side='up'))
# shift to down
print(justify(a, axis=0, side='down'))
# shift to left
print(justify(a, axis=1, side='left'))
# shift to right
print(justify(a, axis=1, side='right'))

The above is the detailed content of How Can I Efficiently Justify a NumPy Array's Non-Zero Elements?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn