numpy-illustrated


Namenumpy-illustrated JSON
Version 0.3.1 PyPI version JSON
download
home_pagehttps://github.com/axil/numpy-illustrated
SummaryHelper functions from the NumPy Illustrated guide
upload_time2023-06-16 02:27:08
maintainer
docs_urlNone
authorLev Maximov
requires_python>=3.7
licenseMIT License
keywords find argmin argmax sort irange numpy first_above first_nonzero
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            п»ї# numpy-illustrated

[![pypi](https://img.shields.io/pypi/v/numpy-illustrated.svg)](https://pypi.python.org/pypi/numpy-illustrated)
[![python](https://img.shields.io/pypi/pyversions/numpy-illustrated.svg)](https://pypi.org/project/numpy-illustrated/)
![pytest](https://github.com/axil/numpy-illustrated/actions/workflows/pytest.yml/badge.svg)
![Coverage Badge](https://github.com/axil/numpy-illustrated/raw/master/img/coverage.svg)
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
[![License](https://img.shields.io/pypi/l/numpy-illustrated)](https://pypi.org/project/numpy-illustrated/)

This repo contains code for a number of helper functions mentioned in the [NumPy Illustrated](https://betterprogramming.pub/numpy-illustrated-the-visual-guide-to-numpy-3b1d4976de1d?sk=57b908a77aa44075a49293fa1631dd9b) guide.

## Installation: 

    pip install numpy-illustrated

## Contents

Three search functions that return immediately after finding the requested value resulting in a 1000x and more speedup for huge arrays:

  - `find`
  - `first_above`
  - `first_nonzero`
    
For better portability, in this library only the pure python/numpy implementation is provided (no speedup).
The actual cython accelerated code is packaged separately in a library called `ndfind`.
If this library is installed with `pip install ndfind` (binaries are provided for python 3.8 .. 3.11 under 
Windows, Linux and MacOS), the faster versions of the functions are used when calling `npi.find`, etc.

If either the array or the value to be found is of floating type, the floating point comparison with relative 
and absolute tolerances is used.

The next four functions act just like `np.argmin`, `np.argmax`, etc., but return a tuple rather than a scalar 
in 2D and above:  

 - `argmin`  
 - `argmax`
 - `nanargmin`  
 - `nanargmax`

Alternative transpose function that converts 1D (row) vector into 2D column vector and back again:  
  - `T_(a)`

Sort function that is able to sort by selected column(s) in ascending/descending order (like sort_values in Pandas):  
  - `sort`

An inclusive range:  
  - `irange`

An alias to concatenate:
  - `concat`

## Documentation

- `find(a, v, rtol=1e-05, atol=1e-08, sorted=False, default=-1, raises=False)`  

Returns the index of the first element in `a` equal to `v`.
If either a or v (or both) is of floating type, the parameters
`atol` (absolute tolerance) and `rtol` (relative tolerance) 
are used for comparison (see `np.isclose()` for details).

Otherwise, returns the `default` value (-1 by default)
or raises a `ValueError` if `raises=True`.

In 2D and above the the values in `a` are always tested and returned in
row-major, C-style order.

For example,
```python
    >>> find([3, 1, 4, 1, 5], 4)
    2
    >>> find([1, 2, 3], 7)
    -1
    >>> find([1.1, 1.2, 1.3], 1.2)
    1
    >>> find(np.arange(0, 1, 0.1), 0.3) 
    3
    >>> find([[3, 8, 4], [5, 2, 7]], 7)
    (1, 2)
    >>> find([[3, 8, 4], [5, 2, 7]], 9)
    -1
    >>> find([999980., 999990., 1e6], 1e6)
    1
    >>> find([999980., 999990., 1e6], 1e6, rtol=1e-9)
    2
```

- `first_above(a, v, sorted=False, missing=-1, raises=False)`

Returns the index of the first element in `a` strictly greater than `v`.
If either a or v (or both) is of floating type, the parameters
`atol` (absolute tolerance) and `rtol` (relative tolerance) 
are used for comparison (see `np.isclose()` for details).

In 2D and above the the values in `a` are always tested and returned in
row-major, C-style order.

If there is no value in `a` greater than `v`, returns the `default` value 
(-1 by default) or raises a `ValueError` if `raises=True`.

Parameters:  
`a` : 1-D array_like  
`v` : scalar
`sorted` : use bisection to further accelerate the search. Only works for sorted arrays.
`missing` : the value to return if no element in `a` is greater than `v`
`raises` : if `True` return an exception instead of returning anything

For example,
```python
    >>> first_above([4, 5, 8, 2, 7], 6)
    2 
    >>> first_above([[4, 5, 8], [2, 7, 3]], 6)
    (0, 2) 
    >>> first_above([5, 6, 7], 9)
    3 
```

-  `first_nonzero(a, missing=-1, raises=False)`

Returns the index of the first nonzero element in `a`.

In 2D and above the the values in `a` are always tested and returned in
row-major, C-style order.

For example,
```python
    >>> first_nonzero([0, 0, 7, 0, 5])
    2
    >>> first_nonzero([False, True, False, False, True])
    1
    >>> first_nonzero([[0, 0, 0, 0], [0, 0, 5, 3]])
    (1, 2)
```

- `argmin(a)`

Returns the index of the minimum value.
The result is scalar in 1D case and tuple of indices in 2D and above.
If the maximum is encountered several times, returns the first match
in the C order (irrespectively of the order of the array itself).
E.g.:
```python
    >>> argmin([4, 3, 5])
    1
    >>> argmin([[4, 8, 5], [9, 3, 1]])
    (1, 2)
```

- `argmax(a)`

Returns the index of the maximum value.
The result is scalar in 1D case and tuple of indices in 2D and above.
If the maximum is encountered several times, returns the first match
in the C order (irrespectively of the order of the array itself).
E.g.:
```python
    >>> argmax([4, 5, 3])
    1
    >>> argmax([[4, 3, 5], [5, 4, 3]])
    (0, 2)
```

- `nanargmin(a)`

Returns the index of the minimum value.
The result is scalar in 1D case and tuple of indices in 2D and above.
If the maximum is encountered several times, returns the first match
in the C order (irrespectively of the order of the array itself).
E.g.:
```python
    >>> nanargmin([4, 3, nan])
    1
    >>> nanargmin([[4, 8, 5], [9, 3, 1]])
    (1, 2)
```

- `nanargmax(a)`

Returns the index of the maximum value.
The result is scalar in 1D case and tuple of indices in 2D and above.
If the maximum is encountered several times, returns the first match
in the C order (irrespectively of the order of the array itself).
E.g.:
```
    >>> nanargmax([nan,5,3])
    1
    >>> nanargmax([[4,3,5], [5,nan,3]])
    (0, 2)
```

- `T_(x)`

Returns a view of the array with axes transposed:
  - transposes a matrix just like the original T;
  - transposes 1D array to a 2D column-vector and vica versa;
  - transposes (a less commonly used) 2D row-vector to a 2D column-vector;
  - for 3D arrays and above swaps the last two dimensions.
E.g.:
```python
    >>> T_(np.array([[1, 2], [3, 4]]))
    array([[1, 3],
           [2, 4]])
    >>> T_(np.array([1, 2, 3]))
    array([[1],
           [2],
           [3]])
    >>> T_(np.array([[1],
                     [2],
                     [3]])
    array([1, 2, 3])
    >>> T_(np.array([[1, 2, 3]]))
    array([[1],
           [2],
           [3]])
```

- `sort(a, by=None, axis=0, ascending=True)`

Rearranges the rows so that the result is sorted by the specified columns
An extension of `sort` that allows sorting by column(s), ascending and descending.

If by is a list [c1, c2, ..., cn], sorts by the column c1, resolving the ties using
the column c2, and so on until cn (just like in pandas). Unlike pandas, the columns
not present in the `by` argument are used for resolving the remaining ties in the
left to right order.

`by=None` is the same as by=[0, 1, 2, ..., a.shape[-1]]

`ascending` can be either be a scalar or a list.

For example:
```python
    >>>  sort([[1, 2, 3],
               [3, 1, 5],
               [1, 0, 6]])
    array([[1, 0, 6],
           [1, 2, 3],
           [3, 1, 5]])
```

- `irange(start, stop, step=1, dtype=None, tol=1e-6)`

Returns an evenly spaced array from start to stop inclusively.
If the range `stop-start` is not evenly divisible by step (=if the calculated number 
of steps is further from the nearest integer than `tol`), raises a ValueError 
exception.

- `concat`

Just a shorter alias to `np.concatenate`

## Testing

Run `pytest` in the project root.



            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/axil/numpy-illustrated",
    "name": "numpy-illustrated",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": "",
    "keywords": "find,argmin,argmax,sort,irange,numpy,first_above,first_nonzero",
    "author": "Lev Maximov",
    "author_email": "lev.maximov@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/50/42/7c4870f49d95783950a0b3330b1ab0d9505384cecb604ada5fd17a3490a1/numpy-illustrated-0.3.1.tar.gz",
    "platform": null,
    "description": "\u043f\u00bb\u0457# numpy-illustrated\r\n\r\n[![pypi](https://img.shields.io/pypi/v/numpy-illustrated.svg)](https://pypi.python.org/pypi/numpy-illustrated)\r\n[![python](https://img.shields.io/pypi/pyversions/numpy-illustrated.svg)](https://pypi.org/project/numpy-illustrated/)\r\n![pytest](https://github.com/axil/numpy-illustrated/actions/workflows/pytest.yml/badge.svg)\r\n![Coverage Badge](https://github.com/axil/numpy-illustrated/raw/master/img/coverage.svg)\r\n[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)\r\n[![License](https://img.shields.io/pypi/l/numpy-illustrated)](https://pypi.org/project/numpy-illustrated/)\r\n\r\nThis repo contains code for a number of helper functions mentioned in the [NumPy Illustrated](https://betterprogramming.pub/numpy-illustrated-the-visual-guide-to-numpy-3b1d4976de1d?sk=57b908a77aa44075a49293fa1631dd9b) guide.\r\n\r\n## Installation: \r\n\r\n    pip install numpy-illustrated\r\n\r\n## Contents\r\n\r\nThree search functions that return immediately after finding the requested value resulting in a 1000x and more speedup for huge arrays:\r\n\r\n  - `find`\r\n  - `first_above`\r\n  - `first_nonzero`\r\n    \r\nFor better portability, in this library only the pure python/numpy implementation is provided (no speedup).\r\nThe actual cython accelerated code is packaged separately in a library called `ndfind`.\r\nIf this library is installed with `pip install ndfind` (binaries are provided for python 3.8 .. 3.11 under \r\nWindows, Linux and MacOS), the faster versions of the functions are used when calling `npi.find`, etc.\r\n\r\nIf either the array or the value to be found is of floating type, the floating point comparison with relative \r\nand absolute tolerances is used.\r\n\r\nThe next four functions act just like `np.argmin`, `np.argmax`, etc., but return a tuple rather than a scalar \r\nin 2D and above:  \r\n\r\n - `argmin`  \r\n - `argmax`\r\n - `nanargmin`  \r\n - `nanargmax`\r\n\r\nAlternative transpose function that converts 1D (row) vector into 2D column vector and back again:  \r\n  - `T_(a)`\r\n\r\nSort function that is able to sort by selected column(s) in ascending/descending order (like sort_values in Pandas):  \r\n  - `sort`\r\n\r\nAn inclusive range:  \r\n  - `irange`\r\n\r\nAn alias to concatenate:\r\n  - `concat`\r\n\r\n## Documentation\r\n\r\n- `find(a, v, rtol=1e-05, atol=1e-08, sorted=False, default=-1, raises=False)`  \r\n\r\nReturns the index of the first element in `a` equal to `v`.\r\nIf either a or v (or both) is of floating type, the parameters\r\n`atol` (absolute tolerance) and `rtol` (relative tolerance) \r\nare used for comparison (see `np.isclose()` for details).\r\n\r\nOtherwise, returns the `default` value (-1 by default)\r\nor raises a `ValueError` if `raises=True`.\r\n\r\nIn 2D and above the the values in `a` are always tested and returned in\r\nrow-major, C-style order.\r\n\r\nFor example,\r\n```python\r\n    >>> find([3, 1, 4, 1, 5], 4)\r\n    2\r\n    >>> find([1, 2, 3], 7)\r\n    -1\r\n    >>> find([1.1, 1.2, 1.3], 1.2)\r\n    1\r\n    >>> find(np.arange(0, 1, 0.1), 0.3) \r\n    3\r\n    >>> find([[3, 8, 4], [5, 2, 7]], 7)\r\n    (1, 2)\r\n    >>> find([[3, 8, 4], [5, 2, 7]], 9)\r\n    -1\r\n    >>> find([999980., 999990., 1e6], 1e6)\r\n    1\r\n    >>> find([999980., 999990., 1e6], 1e6, rtol=1e-9)\r\n    2\r\n```\r\n\r\n- `first_above(a, v, sorted=False, missing=-1, raises=False)`\r\n\r\nReturns the index of the first element in `a` strictly greater than `v`.\r\nIf either a or v (or both) is of floating type, the parameters\r\n`atol` (absolute tolerance) and `rtol` (relative tolerance) \r\nare used for comparison (see `np.isclose()` for details).\r\n\r\nIn 2D and above the the values in `a` are always tested and returned in\r\nrow-major, C-style order.\r\n\r\nIf there is no value in `a` greater than `v`, returns the `default` value \r\n(-1 by default) or raises a `ValueError` if `raises=True`.\r\n\r\nParameters:  \r\n`a` : 1-D array_like  \r\n`v` : scalar\r\n`sorted` : use bisection to further accelerate the search. Only works for sorted arrays.\r\n`missing` : the value to return if no element in `a` is greater than `v`\r\n`raises` : if `True` return an exception instead of returning anything\r\n\r\nFor example,\r\n```python\r\n    >>> first_above([4, 5, 8, 2, 7], 6)\r\n    2 \r\n    >>> first_above([[4, 5, 8], [2, 7, 3]], 6)\r\n    (0, 2) \r\n    >>> first_above([5, 6, 7], 9)\r\n    3 \r\n```\r\n\r\n-  `first_nonzero(a, missing=-1, raises=False)`\r\n\r\nReturns the index of the first nonzero element in `a`.\r\n\r\nIn 2D and above the the values in `a` are always tested and returned in\r\nrow-major, C-style order.\r\n\r\nFor example,\r\n```python\r\n    >>> first_nonzero([0, 0, 7, 0, 5])\r\n    2\r\n    >>> first_nonzero([False, True, False, False, True])\r\n    1\r\n    >>> first_nonzero([[0, 0, 0, 0], [0, 0, 5, 3]])\r\n    (1, 2)\r\n```\r\n\r\n- `argmin(a)`\r\n\r\nReturns the index of the minimum value.\r\nThe result is scalar in 1D case and tuple of indices in 2D and above.\r\nIf the maximum is encountered several times, returns the first match\r\nin the C order (irrespectively of the order of the array itself).\r\nE.g.:\r\n```python\r\n    >>> argmin([4, 3, 5])\r\n    1\r\n    >>> argmin([[4, 8, 5], [9, 3, 1]])\r\n    (1, 2)\r\n```\r\n\r\n- `argmax(a)`\r\n\r\nReturns the index of the maximum value.\r\nThe result is scalar in 1D case and tuple of indices in 2D and above.\r\nIf the maximum is encountered several times, returns the first match\r\nin the C order (irrespectively of the order of the array itself).\r\nE.g.:\r\n```python\r\n    >>> argmax([4, 5, 3])\r\n    1\r\n    >>> argmax([[4, 3, 5], [5, 4, 3]])\r\n    (0, 2)\r\n```\r\n\r\n- `nanargmin(a)`\r\n\r\nReturns the index of the minimum value.\r\nThe result is scalar in 1D case and tuple of indices in 2D and above.\r\nIf the maximum is encountered several times, returns the first match\r\nin the C order (irrespectively of the order of the array itself).\r\nE.g.:\r\n```python\r\n    >>> nanargmin([4, 3, nan])\r\n    1\r\n    >>> nanargmin([[4, 8, 5], [9, 3, 1]])\r\n    (1, 2)\r\n```\r\n\r\n- `nanargmax(a)`\r\n\r\nReturns the index of the maximum value.\r\nThe result is scalar in 1D case and tuple of indices in 2D and above.\r\nIf the maximum is encountered several times, returns the first match\r\nin the C order (irrespectively of the order of the array itself).\r\nE.g.:\r\n```\r\n    >>> nanargmax([nan,5,3])\r\n    1\r\n    >>> nanargmax([[4,3,5], [5,nan,3]])\r\n    (0, 2)\r\n```\r\n\r\n- `T_(x)`\r\n\r\nReturns a view of the array with axes transposed:\r\n  - transposes a matrix just like the original T;\r\n  - transposes 1D array to a 2D column-vector and vica versa;\r\n  - transposes (a less commonly used) 2D row-vector to a 2D column-vector;\r\n  - for 3D arrays and above swaps the last two dimensions.\r\nE.g.:\r\n```python\r\n    >>> T_(np.array([[1, 2], [3, 4]]))\r\n    array([[1, 3],\r\n           [2, 4]])\r\n    >>> T_(np.array([1, 2, 3]))\r\n    array([[1],\r\n           [2],\r\n           [3]])\r\n    >>> T_(np.array([[1],\r\n                     [2],\r\n                     [3]])\r\n    array([1, 2, 3])\r\n    >>> T_(np.array([[1, 2, 3]]))\r\n    array([[1],\r\n           [2],\r\n           [3]])\r\n```\r\n\r\n- `sort(a, by=None, axis=0, ascending=True)`\r\n\r\nRearranges the rows so that the result is sorted by the specified columns\r\nAn extension of `sort` that allows sorting by column(s), ascending and descending.\r\n\r\nIf by is a list [c1, c2, ..., cn], sorts by the column c1, resolving the ties using\r\nthe column c2, and so on until cn (just like in pandas). Unlike pandas, the columns\r\nnot present in the `by` argument are used for resolving the remaining ties in the\r\nleft to right order.\r\n\r\n`by=None` is the same as by=[0, 1, 2, ..., a.shape[-1]]\r\n\r\n`ascending` can be either be a scalar or a list.\r\n\r\nFor example:\r\n```python\r\n    >>>  sort([[1, 2, 3],\r\n               [3, 1, 5],\r\n               [1, 0, 6]])\r\n    array([[1, 0, 6],\r\n           [1, 2, 3],\r\n           [3, 1, 5]])\r\n```\r\n\r\n- `irange(start, stop, step=1, dtype=None, tol=1e-6)`\r\n\r\nReturns an evenly spaced array from start to stop inclusively.\r\nIf the range `stop-start` is not evenly divisible by step (=if the calculated number \r\nof steps is further from the nearest integer than `tol`), raises a ValueError \r\nexception.\r\n\r\n- `concat`\r\n\r\nJust a shorter alias to `np.concatenate`\r\n\r\n## Testing\r\n\r\nRun `pytest` in the project root.\r\n\r\n\r\n",
    "bugtrack_url": null,
    "license": "MIT License",
    "summary": "Helper functions from the NumPy Illustrated guide",
    "version": "0.3.1",
    "project_urls": {
        "Homepage": "https://github.com/axil/numpy-illustrated"
    },
    "split_keywords": [
        "find",
        "argmin",
        "argmax",
        "sort",
        "irange",
        "numpy",
        "first_above",
        "first_nonzero"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "329f69e62d30f280272be2c6cb9693ce658b64f26b3ff35ebd7c9c565bc78eed",
                "md5": "6772760536861964b996944fc789b6cc",
                "sha256": "9299ae7be6c9026a21034795f200376dad17ff1aae74be0c5417823296a3b28f"
            },
            "downloads": -1,
            "filename": "numpy_illustrated-0.3.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "6772760536861964b996944fc789b6cc",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 9050,
            "upload_time": "2023-06-16T02:27:06",
            "upload_time_iso_8601": "2023-06-16T02:27:06.413157Z",
            "url": "https://files.pythonhosted.org/packages/32/9f/69e62d30f280272be2c6cb9693ce658b64f26b3ff35ebd7c9c565bc78eed/numpy_illustrated-0.3.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "50427c4870f49d95783950a0b3330b1ab0d9505384cecb604ada5fd17a3490a1",
                "md5": "b99262568aba4ba44bed3309cd3a3b0d",
                "sha256": "adbb79be13b82d4ac86c6f4b1ec2c4dc2f0e86a0caf47ce4258df754a989f368"
            },
            "downloads": -1,
            "filename": "numpy-illustrated-0.3.1.tar.gz",
            "has_sig": false,
            "md5_digest": "b99262568aba4ba44bed3309cd3a3b0d",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 9819,
            "upload_time": "2023-06-16T02:27:08",
            "upload_time_iso_8601": "2023-06-16T02:27:08.203449Z",
            "url": "https://files.pythonhosted.org/packages/50/42/7c4870f49d95783950a0b3330b1ab0d9505384cecb604ada5fd17a3490a1/numpy-illustrated-0.3.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-06-16 02:27:08",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "axil",
    "github_project": "numpy-illustrated",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [],
    "lcname": "numpy-illustrated"
}
        
Elapsed time: 1.24724s