Python add index to array
You can also construct a confusion matrix right away, instead of adding indices. For Example: Show
Python doesn’t have a specific data type to represent arrays. The following can be used to represent arrays in Python: If we are using List as an array, the following methods can be used to add elements to it: Example 1: Adding elements to an array using append() function Output:
Example 2: Adding elements to an array using extend() function my_input = ['Engineering', 'Medical'] input1 = [40, 30, 20, 10] my_input.extend(input1) print(my_input) Output:
Example 3: Adding elements to an array using insert() function my_input = [1, 2, 3, 4, 5] print(f'Current Numbers List {my_input}') number = int(input("Please enter a number to be added:\n")) index = int(input(f'Enter the index between 0 and {len(my_input) - 1} to add the given number:\n')) my_input.insert(index, number) print(f'Updated List {my_input}') Output: Output-Insert Function2. Adding to an array using array moduleIf we are using the array module, the following methods can be used to add elements to it:
Example: import array s1 = array.array('i', [1, 2, 3]) s2 = array.array('i', [4, 5, 6]) print(s1) print(s2) s3 = s1 + s2 print(s3) s1.append(4) print(s1) s1.insert(0, 10) print(s1) s1.extend(s2) print(s1) Output: Output Array Module3. Addition of elements to NumPy arrayWe can add elements to a NumPy array using the following methods:
Example: import numpy # insert function arr1_insert = numpy.array([1, 23, 33]) arr2_insert = numpy.insert(arr1_insert, 1, 91) print(arr2_insert) # append function arr1_append = numpy.array([4, 2, 1]) arr2_append = numpy.append (arr1_append, [12, 13, 14]) print(arr2_append) Output:
ConclusionThus, in this article, we have implemented possible ways to add elements to an array. References
Most of the following examples show the use of indexing when referencing data in an array. The examples work just as well when assigning to an array. See Assigning values to indexed arrays for specific examples and explanations on how assignments work. Note that in Python, Basic indexing#Single element indexing#Single element indexing works exactly like that for other standard Python sequences. It is 0-based, and accepts negative indices for indexing from the end of the array. >>> x = np.arange(10) >>> x[2] 2 >>> x[-2] 8 It is not necessary to separate each dimension’s index into its own set of square brackets. >>> x.shape = (2, 5) # now x is 2-dimensional >>> x[1, 3] 8 >>> x[1, -1] 9 Note that if one indexes a multidimensional array with fewer indices than dimensions, one gets a subdimensional array. For example: >>> x[0] array([0, 1, 2, 3, 4]) That is, each index specified selects the array corresponding to the rest of the dimensions selected. In the above example, choosing 0 means that the remaining dimension of length 5 is being left unspecified, and that what is returned is an array of that dimensionality and size. It must be noted that the returned array is a view, i.e., it is not a copy of the original, but points to the same values in memory as does the original array. In this case, the 1-D array at the first position (0) is returned. So using a single index on the returned array, results in a single element being returned. That is: So note that Note NumPy uses C-order indexing. That means that the last index usually represents the most rapidly changing memory location, unlike Fortran or IDL, where the first index represents the most rapidly changing location in memory. This difference represents a great potential for confusion. Slicing and striding#Basic slicing extends Python’s basic concept of slicing to N dimensions. Basic slicing occurs when obj is a
The simplest case of indexing with N integers returns an array scalar representing the corresponding item. As in Python, all indices are zero-based: for the i-th index \(n_i\), the valid range is \(0 \le n_i < d_i\) where \(d_i\) is the i-th element of the shape of the array. Negative indices are interpreted as counting from the end of the array (i.e., if \(n_i < 0\), it means \(n_i + d_i\)). All arrays generated by basic slicing are always views of the original array. Note NumPy slicing creates a
view instead of a copy as in the case of built-in Python sequences such as string, tuple and list. Care must be taken when extracting a small portion from a large array which becomes useless after the extraction, because the small portion extracted contains a reference to the large original array whose memory will not be released until all arrays derived from it are garbage-collected. In such cases an
explicit The standard rules of sequence slicing apply to basic slicing on a per-dimension basis (including using a step index). Some useful concepts to remember include:
Dimensional indexing tools#There are some tools to facilitate the easy matching of array shapes with expressions and in assignments.
>>> x[..., 0] array([[1, 2, 3], [4, 5, 6]]) This is equivalent to: >>> x[:, :, 0] array([[1, 2, 3], [4, 5, 6]]) Each >>> x[:, np.newaxis, :, :].shape (2, 1, 3, 1) >>> x[:, None, :, :].shape (2, 1, 3, 1) This can be handy to combine two arrays in a way that otherwise would require explicit reshaping operations. For example: >>> x = np.arange(5) >>> x[:, np.newaxis] + x[np.newaxis, :] array([[0, 1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7], [4, 5, 6, 7, 8]]) Advanced indexing#Advanced indexing is triggered when the selection object, obj, is a non-tuple sequence object, an
Advanced indexing always returns a copy of the data (contrast with basic slicing that returns a view). Warning The definition of advanced indexing means that Also recognize that Integer array indexing#Integer array indexing allows selection of arbitrary items in the array based on their N-dimensional index. Each integer array represents a number of indices into that dimension. Negative values are permitted in the index arrays and work as they do with single indices or slices: >>> x = np.arange(10, 1, -1) >>> x array([10, 9, 8, 7, 6, 5, 4, 3, 2]) >>> x[np.array([3, 3, 1, 8])] array([7, 7, 9, 2]) >>> x[np.array([3, 3, -3, 8])] array([7, 7, 4, 2]) If the index values are out of bounds then an >>> x = np.array([[1, 2], [3, 4], [5, 6]]) >>> x[np.array([1, -1])] array([[3, 4], [5, 6]]) >>> x[np.array([3, 4])] Traceback (most recent call last): ... IndexError: index 3 is out of bounds for axis 0 with size 3 When the index consists of as many integer arrays as dimensions of the array being indexed, the indexing is straightforward, but different from slicing. Advanced indices always are broadcast and iterated as one: result[i_1, ..., i_M] == x[ind_1[i_1, ..., i_M], ind_2[i_1, ..., i_M], ..., ind_N[i_1, ..., i_M]] Note that the resulting shape is identical to the (broadcast) indexing array shapes Indexing with multidimensional index arrays tend to be more unusual uses, but they are permitted, and they are useful for some problems. We’ll start with the simplest multidimensional case: >>> y = np.arange(35).reshape(5, 7) >>> y array([[ 0, 1, 2, 3, 4, 5, 6], [ 7, 8, 9, 10, 11, 12, 13], [14, 15, 16, 17, 18, 19, 20], [21, 22, 23, 24, 25, 26, 27], [28, 29, 30, 31, 32, 33, 34]]) >>> y[np.array([0, 2, 4]), np.array([0, 1, 2])] array([ 0, 15, 30]) In this case, if the index arrays have a matching shape, and there is an index array for each dimension of the array being indexed, the resultant array has the same shape as the index arrays, and the values correspond to the index set for each position in the index arrays. In this example, the first index value is 0 for both index arrays, and thus the first value of the resultant array is If the index arrays do not have the same shape, there is an attempt to broadcast them to the same shape. If they cannot be broadcast to the same shape, an exception is raised: >>> y[np.array([0, 2, 4]), np.array([0, 1])] Traceback (most recent call last): ... IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (3,) (2,) The broadcasting mechanism permits index arrays to be combined with scalars for other indices. The effect is that the scalar value is used for all the corresponding values of the index arrays: >>> y[np.array([0, 2, 4]), 1] array([ 1, 15, 29]) Jumping to the next level of complexity, it is possible to only partially index an array with index arrays. It takes a bit of thought to understand what happens in such cases. For example if we just use one index array with y: >>> y[np.array([0, 2, 4])] array([[ 0, 1, 2, 3, 4, 5, 6], [14, 15, 16, 17, 18, 19, 20], [28, 29, 30, 31, 32, 33, 34]]) It results in the construction of a new array where each value of the index array selects one row from the array being indexed and the resultant array has the resulting shape (number of index elements, size of row). In general, the shape of the resultant array will be the concatenation of the shape of the index array (or the shape that all the index arrays were broadcast to) with the shape of any unused dimensions (those not indexed) in the array being indexed. Example From each row, a specific element should be selected. The row index is just >>> x = np.array([[1, 2], [3, 4], [5, 6]]) >>> x[[0, 1, 2], [0, 1, 0]] array([1, 4, 5]) To achieve a
behaviour similar to the basic slicing above, broadcasting can be used. The function Example From a 4x3 array the corner elements should be selected using advanced indexing. Thus all elements for which the column is one of >>> x = np.array([[ 0, 1, 2], ... [ 3, 4, 5], ... [ 6, 7, 8], ... [ 9, 10, 11]]) >>> rows = np.array([[0, 0], ... [3, 3]], dtype=np.intp) >>> columns = np.array([[0, 2], ... [0, 2]], dtype=np.intp) >>> x[rows, columns] array([[ 0, 2], [ 9, 11]]) However, since the indexing arrays above just repeat themselves, broadcasting can be used (compare operations such as >>> rows = np.array([0, 3], dtype=np.intp) >>> columns = np.array([0, 2], dtype=np.intp) >>> rows[:, np.newaxis] array([[0], [3]]) >>> x[rows[:, np.newaxis], columns] array([[ 0, 2], [ 9, 11]]) This broadcasting can also be achieved using the function
>>> x[np.ix_(rows, columns)] array([[ 0, 2], [ 9, 11]]) Note that without the >>> x[rows, columns] array([ 0, 11]) This difference is the most important thing to remember about indexing with multiple advanced indices. Example A real-life example of where advanced indexing may be useful is for a color lookup table where we want to map the values of an image into RGB triples for display. The lookup table could have a shape (nlookup, 3). Indexing such an array with an image with shape (ny, nx) with dtype=np.uint8 (or any integer type so long as values are with the bounds of the lookup table) will result in an array of shape (ny, nx, 3) where a triple of RGB values is associated with each pixel location. Boolean array indexing#This advanced indexing occurs when obj is an array object of Boolean type, such as may be returned from comparison operators. A single boolean index array is practically identical to If A common use case for this is filtering for desired element values. For example, one may wish to select all entries from an array which are not >>> x = np.array([[1., 2.], [np.nan, 3.], [np.nan, np.nan]]) >>> x[~np.isnan(x)] array([1., 2., 3.]) Or wish to add a constant to all negative elements: >>> x = np.array([1., -1., -2., 3]) >>> x[x < 0] += 20 >>> x array([ 1., 19., 18., 3.]) In
general if an index includes a Boolean array, the result will be identical to inserting If there is only one Boolean array and no integer indexing array present, this is straightforward. Care must only be taken to make sure that the boolean index has exactly as many dimensions as it is supposed to work with. In general, when the boolean array
has fewer dimensions than the array being indexed, this is equivalent to >>> x = np.arange(35).reshape(5, 7) >>> b = x > 20 >>> b[:, 5] array([False, False, False, True, True]) >>> x[b[:, 5]] array([[21, 22, 23, 24, 25, 26, 27], [28, 29, 30, 31, 32, 33, 34]]) Here the 4th and 5th rows are selected from the indexed array and combined to make a 2-D array. Example From an array, select all rows which sum up to less or equal two: >>> x = np.array([[0, 1], [1, 1], [2, 2]]) >>> rowsum = x.sum(-1) >>> x[rowsum <= 2, :] array([[0, 1], [1, 1]]) Combining multiple Boolean indexing arrays or a Boolean with an integer indexing array can best be understood with the Example Use boolean indexing to select all rows adding up to an even number. At the same time columns 0 and 2 should be selected with an advanced integer index. Using the
>>> x = np.array([[ 0, 1, 2], ... [ 3, 4, 5], ... [ 6, 7, 8], ... [ 9, 10, 11]]) >>> rows = (x.sum(-1) % 2) == 0 >>> rows array([False, True, False, True]) >>> columns = [0, 2] >>> x[np.ix_(rows, columns)] array([[ 3, 5], [ 9, 11]]) Without the Or without >>> rows = rows.nonzero()[0] >>> x[rows[:, np.newaxis], columns] array([[ 3, 5], [ 9, 11]]) Example Use a 2-D boolean array of shape (2, 3) with four True elements to select rows from a 3-D array of shape (2, 3, 5) results in a 2-D result of shape (4, 5): >>> x = np.arange(30).reshape(2, 3, 5) >>> x array([[[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14]], [[15, 16, 17, 18, 19], [20, 21, 22, 23, 24], [25, 26, 27, 28, 29]]]) >>> b = np.array([[True, True, False], [False, True, True]]) >>> x[b] array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [20, 21, 22, 23, 24], [25, 26, 27, 28, 29]]) Combining advanced and basic indexing#When there is at least one slice ( In the simplest case, there is only a single advanced index combined with a slice. For example: >>> y = np.arange(35).reshape(5,7) >>> y[np.array([0, 2, 4]), 1:3] array([[ 1, 2], [15, 16], [29, 30]]) In effect, the slice and index array operation are independent. The slice operation extracts columns with index 1 and 2, (i.e. the 2nd and 3rd columns), followed by the index array operation which extracts rows with index 0, 2 and 4 (i.e the first, third and fifth rows). This is equivalent to: >>> y[:, 1:3][np.array([0, 2, 4]), :] array([[ 1, 2], [15, 16], [29, 30]]) A single advanced index can, for example, replace a slice and the result array will be the same. However, it is a copy and may have a different memory layout. A slice is preferable when it is possible. For example: >>> x = np.array([[ 0, 1, 2], ... [ 3, 4, 5], ... [ 6, 7, 8], ... [ 9, 10, 11]]) >>> x[1:2, 1:3] array([[4, 5]]) >>> x[1:2, [1, 2]] array([[4, 5]]) The easiest way to understand a combination of multiple advanced indices may be to think in terms of the resulting shape. There are two parts to the indexing operation, the subspace defined by the basic indexing (excluding integers) and the subspace from the advanced indexing part. Two cases of index combination need to be distinguished:
In the first case, the dimensions resulting from the advanced indexing operation come first in the result array, and the subspace dimensions after that. In the second case, the dimensions from the advanced indexing operations are inserted into the result array at the same spot as they were in the initial array (the latter logic is what makes simple advanced indexing behave just like slicing). Example Suppose Example Let Example Slicing can be combined with broadcasted boolean indices: >>> x = np.arange(35).reshape(5, 7) >>> b = x > 20 >>> b array([[False, False, False, False, False, False, False], [False, False, False, False, False, False, False], [False, False, False, False, False, False, False], [ True, True, True, True, True, True, True], [ True, True, True, True, True, True, True]]) >>> x[b[:, 5], 1:3] array([[22, 23], [29, 30]]) Field access#If the
Indexing Indexing into a structured array can also be done with a list of field names, e.g. If the accessed field is a sub-array, the dimensions of the sub-array are appended to the shape of the result. For example: >>> x = np.zeros((2, 2), dtype=[('a', np.int32), ('b', np.float64, (3, 3))]) >>> x['a'].shape (2, 2) >>> x['a'].dtype dtype('int32') >>> x['b'].shape (2, 2, 3, 3) >>> x['b'].dtype dtype('float64') Flat Iterator indexing#
Assigning values to indexed arrays#As mentioned, one can select a subset of an array to assign to using a single index, slices, and index and mask arrays. The value being assigned to the indexed array must be shape consistent (the same shape or broadcastable to the shape the index produces). For example, it is permitted to assign a constant to a slice: >>> x = np.arange(10) >>> x[2:7] = 1 or an array of the right size: >>> x[2:7] = np.arange(5) Note that assignments may result in changes if assigning higher types to lower types (like floats to ints) or even exceptions (assigning complex to floats or ints): >>> x[1] = 1.2 >>> x[1] 1 >>> x[1] = 1.2j Traceback (most recent call last): ... TypeError: can't convert complex to int Unlike some of the references (such as array and mask indices) assignments are always made to the original data in the array (indeed, nothing else would make sense!). Note though, that some actions may not work as one may naively expect. This particular example is often surprising to people: >>> x = np.arange(0, 50, 10) >>> x array([ 0, 10, 20, 30, 40]) >>> x[np.array([1, 1, 3, 1])] += 1 >>> x array([ 0, 11, 20, 31, 40]) Where people expect that the 1st location will be incremented by 3. In fact, it will only be incremented by 1. The reason is that a new array is extracted from the original (as a temporary) containing the values at 1, 1, 3, 1, then the value 1 is added to the temporary, and
then the temporary is assigned back to the original array. Thus the value of the array at Dealing with variable numbers of indices within programs#The indexing syntax is very powerful but limiting when dealing with a variable number of indices. For example, if you want to write a function that can handle arguments with various numbers of dimensions without having to write special case code for each number of possible dimensions, how can that be done? If one supplies to the index a tuple, the tuple will be interpreted as a list of indices. For example: >>> z = np.arange(81).reshape(3, 3, 3, 3) >>> indices = (1, 1, 1, 1) >>> z[indices] 40 So one can use code to construct tuples of any number of indices and then use these within an index. Slices can be specified within programs by using the slice() function in Python. For example: >>> indices = (1, 1, 1, slice(0, 2)) # same as [1, 1, 1, 0:2] >>> z[indices] array([39, 40]) Likewise, ellipsis can be specified by code by using the Ellipsis object: >>> indices = (1, Ellipsis, 1) # same as [1, ..., 1] >>> z[indices] array([[28, 31, 34], [37, 40, 43], [46, 49, 52]]) For this reason, it is possible to use the
output from the Because of the special treatment of tuples, they are not automatically converted to an array as a list would be. As an example: >>> z[[1, 1, 1, 1]] # produces a large array array([[[[27, 28, 29], [30, 31, 32], ... >>> z[(1, 1, 1, 1)] # returns a single value 40 Detailed notes#These are some detailed notes, which are not of importance for day to day indexing (in no particular order):
How do you add an index to an array in Python?Adding to an array using array module
By using append() function : It adds elements to the end of the array. By using insert() function : It inserts the elements at the given index. By using extend() function : It elongates the list by appending elements from both the lists.
Can you index an array Python?Elements in NumPy arrays can be accessed by indexing. Indexing is an operation that pulls out a select set of values from an array. The index of a value in an array is that value's location within the array.
Can I index a NumPy array?Array indexing is the same as accessing an array element. You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.
How do you add a value to an index in Python?How to Add an Element to a Python List at an Index?. Use the list insert method list. insert(index, element) .. Use slice assignment lst[index:index] = [element] to overwrite the empty slice with a list of one element.. Use list concatenation with slicing lst[:2] + ['Alice'] + lst[2:] to create a new list object.. |