Working with NDArray
Working with NDArray
Get shape of array
We can get shape of an array by accessing 'shape' property.
import numpy as np
def test_run():
array = np.array([(1, 2, 3), (2, 3, 4)])
print array.shape
print len(array.shape)
print array.shape[0]
print array.shape[1]
if __name__ == "__main__":
test_run()Here we have printed out the shape of the array.
(2, 3)
2
2
3Get size of array
Size of array is returned as sum of all cells in the n-dimension array.
For our example, which contains 6 numbers, it prints out 6.
Type of array
NumPy arrays are homogenous (all the cells must have the same type) and we can get that type for an array.
Here is the type of the array.
Make random numbers the same for every execution
We can set seed for random number generation. Which will make sure that the random numbers are generated always the same.
So, everytime we run this code, we get the same result.
Sum all elements in array
Here is sum.
Sum of each column and row
Here are the sums.
Finding max, min and mean in an array
Her are the values.
There are more functions available, check this page.
Find index of max value
Here is the output.
Glue arrays together
There are many ways to append or connect two arrays. Depends what we really need.
Append one array to another array.
Or we can do the same thing using vstack function.
Or using hstack to do it horizontally.
Add another column into an array.
Slicing array
If you want to slice data, get some specific values of array, you can access it via indices.
First argument ":" makes sure all rows are included. Second argument if more complex. 0 and 3 are saying what values to take. 2 is saying what will be skipped. Here is the output.
Assigning values in array
Here is the output.
Or you can assign value to whole row or column.
Here is the output.
Or you can set list of values to a row.
Indexing
Here is the output.
Filtering data using conditions
Also called masking.
Output.
Multiplication
Output.
Sum arrays
Output.
Last updated
Was this helpful?