Return an array drawn from elements in choicelist, depending on conditions. Parameters ---------- condlist : list of bool ndarrays The list of conditions which determine from which array in `choicelist` the output elements are taken. When multiple conditions are sat
(condlist, choicelist, default=0)
| 767 | |
| 768 | @array_function_dispatch(_select_dispatcher) |
| 769 | def select(condlist, choicelist, default=0): |
| 770 | """ |
| 771 | Return an array drawn from elements in choicelist, depending on conditions. |
| 772 | |
| 773 | Parameters |
| 774 | ---------- |
| 775 | condlist : list of bool ndarrays |
| 776 | The list of conditions which determine from which array in `choicelist` |
| 777 | the output elements are taken. When multiple conditions are satisfied, |
| 778 | the first one encountered in `condlist` is used. |
| 779 | choicelist : list of ndarrays |
| 780 | The list of arrays from which the output elements are taken. It has |
| 781 | to be of the same length as `condlist`. |
| 782 | default : scalar, optional |
| 783 | The element inserted in `output` when all conditions evaluate to False. |
| 784 | |
| 785 | Returns |
| 786 | ------- |
| 787 | output : ndarray |
| 788 | The output at position m is the m-th element of the array in |
| 789 | `choicelist` where the m-th element of the corresponding array in |
| 790 | `condlist` is True. |
| 791 | |
| 792 | See Also |
| 793 | -------- |
| 794 | where : Return elements from one of two arrays depending on condition. |
| 795 | take, choose, compress, diag, diagonal |
| 796 | |
| 797 | Examples |
| 798 | -------- |
| 799 | >>> x = np.arange(6) |
| 800 | >>> condlist = [x<3, x>3] |
| 801 | >>> choicelist = [x, x**2] |
| 802 | >>> np.select(condlist, choicelist, 42) |
| 803 | array([ 0, 1, 2, 42, 16, 25]) |
| 804 | |
| 805 | >>> condlist = [x<=4, x>3] |
| 806 | >>> choicelist = [x, x**2] |
| 807 | >>> np.select(condlist, choicelist, 55) |
| 808 | array([ 0, 1, 2, 3, 4, 25]) |
| 809 | |
| 810 | """ |
| 811 | # Check the size of condlist and choicelist are the same, or abort. |
| 812 | if len(condlist) != len(choicelist): |
| 813 | raise ValueError( |
| 814 | 'list of cases must be same length as list of conditions') |
| 815 | |
| 816 | # Now that the dtype is known, handle the deprecated select([], []) case |
| 817 | if len(condlist) == 0: |
| 818 | raise ValueError("select with an empty condition list is not possible") |
| 819 | |
| 820 | choicelist = [np.asarray(choice) for choice in choicelist] |
| 821 | |
| 822 | try: |
| 823 | intermediate_dtype = np.result_type(*choicelist) |
| 824 | except TypeError as e: |
| 825 | msg = f'Choicelist elements do not have a common dtype: {e}' |
| 826 | raise TypeError(msg) from None |
no outgoing calls