Overall then:
def sum_axis_i(arr, axis, i):
idx = (np.s_[: ], ) * axis + (i, )
return arr[idx].sum()
If you use np.index_exp
, which is very similar to np.s_
, you can write that:
def sum_axis_i(arr, axis, i):
idx = np.index_exp[: ] * axis + np.index_exp[i]
return arr[idx].sum()
You can do it by dynamically creating a tuple
of slice
:
def sum_layer_axis(array, layer, axis):
slicer = tuple(slice(None) if ax != axis
else layer
for ax in range(array.ndim))
return np.sum(array[slicer])
Just to illustrate how this works consider what is interpreted from the slice
:
class Fun(object):
def __getitem__(self, item):
return item
Fun()[: , 2,: ]
#(slice(None, None, None), 2, slice(None, None, None))
So we would need to recreate that (but we don't need to specify 3 times the None
, one is enough). This is possible with a generator expression:
tuple(slice(None) if ax != axis
else layer
for ax in range(array.ndim))
This may not be the most efficient but it should work:
m = np.arange(60).reshape((3, 4, 5))
def my_sum(m, dim, index):
dims = tuple(i
for i in xrange(m.ndim) if i != dim)
return m.sum(axis = dims)[index]
print my_sum(m, 1, 2)
print m[: , 2,: ].sum()
Here's an approach that swaps the first axis with the input axis and then index with the input index, which will select all elements in context and finally sum all those for the final result. The implementation would be a compact one with np.swapaxes
and np.sum
, like so -
def sum_axis_index(m, axis, index):
return m.swapaxes(0, axis)[index].sum()
An ndarray is a (usually fixed-size) multidimensional container of items of the same type and size. The number of dimensions and items in an array is defined by its shape, which is a tuple of N non-negative integers that specify the sizes of each dimension. The type of items in the array is specified by a separate data-type object (dtype), one of which is associated with each ndarray.,Tuple of bytes to step in each dimension when traversing an array.,For reshape, resize, and transpose, the single tuple argument may be replaced with n integers which will be interpreted as an n-tuple.,Rearranges the elements in the array in such a way that the value of the element in kth position is in the position it would be in a sorted array.
>>> x = np.array([[1, 2, 3], [4, 5, 6]], np.int32)
>>> type(x)
<class 'numpy.ndarray'>
>>> x.shape
(2, 3)
>>> x.dtype
dtype('int32')
>>> # The element of x in the * second * row, * third * column, namely, 6. >>>
x[1, 2]
6
>>> y = x[: , 1] >>> y array([2, 5], dtype = int32) >>> y[0] = 9 # this also changes the corresponding element in x >>> y array([9, 5], dtype = int32) >>> x array([ [1, 9, 3], [4, 5, 6] ], dtype = int32)
>>> x = np.arange(27).reshape((3, 3, 3)) >>> 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] ] ]) >>> x.sum(axis = 0) array([ [27, 30, 33], [36, 39, 42], [45, 48, 51] ]) >>> # for sum, axis is the first keyword, so we may omit it, >>> # specifying only its value >>> x.sum(0), x.sum(1), x.sum(2) (array([ [27, 30, 33], [36, 39, 42], [45, 48, 51] ]), array([ [9, 12, 15], [36, 39, 42], [63, 66, 69] ]), array([ [3, 12, 21], [30, 39, 48], [57, 66, 75] ]))
You can slice a range of elements from one-dimensional numpy arrays such as the third, fourth and fifth elements, by specifying an index range: [starting_value, ending_value].,For two-dimensional numpy arrays, you need to specify both a row index and a column index for the element (or range of elements) that you want to access.,You can use avg_monthly_precip[2] to select the third element in (1.85) from this one-dimensional numpy array.,On this page, you will use indexing to select elements within one-dimensional and two-dimensional numpy arrays, a selection process referred to as slicing.
avg_monthly_precip = numpy.array([0.70, 0.75, 1.85])
precip_2002_2013 = numpy.array([ [1.07, 0.44, 1.5], [0.27, 1.13, 1.72] ])
# Import necessary packages import os import numpy as np import earthpy as et
# Download.txt with avg monthly precip(inches) monthly_precip_url = 'https://ndownloader.figshare.com/files/12565616' et.data.get_data(url = monthly_precip_url) # Download.csv of precip data for 2002 and 2013(inches) precip_2002_2013_url = 'https://ndownloader.figshare.com/files/12707792' et.data.get_data(url = precip_2002_2013_url)
'/root/earth-analytics/data/earthpy-downloads/monthly-precip-2002-2013.csv'
# Set working directory to earth - analytics os.chdir(os.path.join(et.io.HOME, 'earth-analytics'))
Let’s use this to get the shape or dimensions of a 2D & 1D numpy array i.e.,Python’s Numpy Module provides a function to get the dimensions of a Numpy array, ,Python’s Numpy module provides a function to get the number of elements in a Numpy array along axis i.e. ,In this article we will discuss how to count number of elements in a 1D, 2D & 3D Numpy array, also how to count number of rows & columns of a 2D numpy array and number of elements per axis in 3D numpy array.
Python’s Numpy Module provides a function to get the dimensions of a Numpy array,
ndarray.shape
Let’s create a 2D Numpy array i.e.
# Create a 2 D Numpy array list of list arr2D = np.array([ [11, 12, 13, 11], [21, 22, 23, 24], [31, 32, 33, 34] ]) print('2D Numpy Array') print(arr2D)
2 D Numpy Array
[[11 12 13 11]
[21 22 23 24]
[31 32 33 34]]
Python’s Numpy module provides a function to get the number of elements in a Numpy array along axis i.e.
numpy.size(arr, axis = None)
Let’s create a 3D Numpy array i.e.
# Create a 3 D Numpy array list of list of list arr3D = np.array([ [ [11, 12, 13, 11], [21, 22, 23, 24], [31, 32, 33, 34] ], [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3] ] ]) print(arr3D)
The dimensionality of an array specifies the number of indices that are required to uniquely specify one of its entries.,Introduce the indexing and slicing scheme for accessing a multi-dimensional array’s contents,Similar to Python’s sequences, we use 0-based indices and slicing to access the content of an array. However, we must specify an index/slice for each dimension of an array:,Given this indexing scheme, only one integer is needed to specify a unique entry in the array. Similarly only one slice is needed to uniquely specify a subsequence of entries in the array. For this reason, we say that this is a 1-dimensional array. In general, the dimensionality of an array specifies the number of indices that are required to uniquely specify one of its entries.
# A 0 - D array np.array(8) # A 1 - D array, shape - (3, ) np.array([2.3, 0.1, -9.1]) # A 2 - D array, shape - (3, 2) np.array([ [93, 95], [84, 100], [99, 87] ]) # A 3 - D array, shape - (2, 2, 2) np.array([ [ [0, 1], [2, 3] ], [ [4, 5], [6, 7] ] ])
>>> import numpy as np # A 3 - D array >>> x = np.array([ [ [0, 1], ...[2, 3] ], ... ...[ [4, 5], ...[6, 7] ] ]) # get: sheet - 0, both rows, flip order of columns >>> x[0,: , ::-1] array([ [1, 0], [3, 2] ])
>>> simple_array = np.array([2.3, 0.1, -9.1])
+ -- -- -- + -- -- -- + -- -- -- + | 2.3 | 0.1 | -9.1 | + -- -- -- + -- -- -- + -- -- -- + 0 1 2 - 3 - 2 - 1
>>> simple_array[0]
2.3
>>>
simple_array[-2]
0.1
>>>
simple_array[1: 3]
array([0.1, -9.1])
>>>
simple_array[3]
IndexError: index 3 is out of bounds
for axis 0 with size 3
# using a 1 - dimensional array to store the grades >>> grades = np.array([93, 95, 84, 100, 99, 87])
Last Updated : 28 Jun, 2021,GATE CS 2021 Syllabus
Example :
[
[1, 2, 3],
[4, 2, 5]
]
Here, rank = 2(as it is 2 - dimensional or it has 2 axes)
First dimension(axis) length = 2, second dimension has length = 3
overall shape can be expressed as: (2, 3)
[[ 1, 2, 3], [ 4, 2, 5]] Here, rank = 2 (as it is 2-dimensional or it has 2 axes) First dimension(axis) length = 2, second dimension has length = 3 overall shape can be expressed as: (2, 3)
# Python program to demonstrate # basic array characteristics import numpy as np # Creating array object arr = np.array([ [1, 2, 3], [4, 2, 5] ]) # Printing type of arr object print("Array is of type: ", type(arr)) # Printing array dimensions(axes) print("No. of dimensions: ", arr.ndim) # Printing shape of array print("Shape of array: ", arr.shape) # Printing size(total number of elements) of array print("Size of array: ", arr.size) # Printing type of elements in array print("Array stores elements of type: ", arr.dtype)
Output :
Array is of type: <class 'numpy.ndarray'>
No. of dimensions: 2
Shape of array: (2, 3)
Size of array: 6
Array stores elements of type: int64
- Slicing: Just like lists in python, NumPy arrays can be sliced. As arrays can be multidimensional, you need to specify a slice for each dimension of the array.
- Integer array indexing: In this method, lists are passed for indexing for each dimension. One to one mapping of corresponding elements is done to construct a new arbitrary array.
- Boolean array indexing: This method is used when we want to pick elements from array which satisfy some condition.
# Python program to demonstrate # indexing in numpy import numpy as np # An exemplar array arr = np.array([ [-1, 2, 0, 4], [4, -0.5, 6, 0], [2.6, 0, 7, 8], [3, -7, 4, 2.0] ]) # Slicing array temp = arr[: 2, ::2] print("Array with first 2 rows and alternate" "columns(0 and 2):\n", temp) # Integer array indexing example temp = arr[[0, 1, 2, 3], [3, 2, 1, 0]] print("\nElements at indices (0, 3), (1, 2), (2, 1)," "(3, 0):\n", temp) # boolean array indexing example cond = arr > 0 # cond is a boolean array temp = arr[cond] print("\nElements greater than 0:\n", temp)
# Python program to demonstrate # basic operations on single array import numpy as np a = np.array([1, 2, 5, 3]) # add 1 to every element print("Adding 1 to every element:", a + 1) # subtract 3 from each element print("Subtracting 3 from each element:", a - 3) # multiply each element by 10 print("Multiplying each element by 10:", a * 10) # square each element print("Squaring each element:", a ** 2) # modify existing array a *= 2 print("Doubled each element of original array:", a) # transpose of array a = np.array([ [1, 2, 3], [3, 4, 5], [9, 6, 0] ]) print("\nOriginal array:\n", a) print("Transpose of array:\n", a.T)
# Python program to demonstrate # basic operations on single array import numpy as np a = np.array([1, 2, 5, 3]) # add 1 to every element print("Adding 1 to every element:", a + 1) # subtract 3 from each element print("Subtracting 3 from each element:", a - 3) # multiply each element by 10 print("Multiplying each element by 10:", a * 10) # square each element print("Squaring each element:", a ** 2) # modify existing array a *= 2 print("Doubled each element of original array:", a) # transpose of array a = np.array([ [1, 2, 3], [3, 4, 5], [9, 6, 0] ]) print("\nOriginal array:\n", a) print("Transpose of array:\n", a.T)
Output :
Adding 1 to every element: [2 3 6 4]
Subtracting 3 from each element: [-2 - 1 2 0]
Multiplying each element by 10: [10 20 50 30]
Squaring each element: [1 4 25 9]
Doubled each element of original array: [2 4 10 6]
Original array: [
[1 2 3]
[3 4 5]
[9 6 0]
]
Transpose of array: [
[1 3 9]
[2 4 6]
[3 5 0]
]
# Python program to demonstrate # unary operators in numpy import numpy as np arr = np.array([ [1, 5, 6], [4, 7, 2], [3, 1, 9] ]) # maximum element of array print("Largest element is:", arr.max()) print("Row-wise maximum elements:", arr.max(axis = 1)) # minimum element of array print("Column-wise minimum elements:", arr.min(axis = 0)) # sum of array elements print("Sum of all array elements:", arr.sum()) # cumulative sum along each row print("Cumulative sum along each row:\n", arr.cumsum(axis = 1))
Output :
Largest element is: 9 Row - wise maximum elements: [6 7 9] Column - wise minimum elements: [1 1 2] Sum of all array elements: 38 Cumulative sum along each row: [ [1 6 12] [4 11 13] [3 4 13] ]
# Python program to demonstrate # binary operators in Numpy import numpy as np a = np.array([ [1, 2], [3, 4] ]) b = np.array([ [4, 3], [2, 1] ]) # add arrays print("Array sum:\n", a + b) # multiply arrays(elementwise multiplication) print("Array multiplication:\n", a * b) # matrix multiplication print("Matrix multiplication:\n", a.dot(b))
Output:
Array sum: [
[5 5]
[5 5]
]
Array multiplication: [
[4 6]
[6 4]
]
Matrix multiplication: [
[8 5]
[20 13]
]
Note: All the operations we did above using overloaded operators can be done using ufuncs like np.add, np.subtract, np.multiply, np.divide, np.sum, etc.
# Python program to demonstrate # universal functions in numpy import numpy as np # create an array of sine values a = np.array([0, np.pi / 2, np.pi]) print("Sine values of array elements:", np.sin(a)) # exponential values a = np.array([0, 1, 2, 3]) print("Exponent of array elements:", np.exp(a)) # square root of array values print("Square root of array elements:", np.sqrt(a))
Output:
Sine values of array elements: [0.00000000e+00 1.00000000e+00 1.22464680e-16] Exponent of array elements: [1. 2.71828183 7.3890561 20.08553692] Square root of array elements: [0. 1. 1.41421356 1.73205081]