Friday, May 14, 2021

 Numpy  slicing pattern


The general numpy slicing pattern is : 

        array[rows_start : rows_end + 1 : rows_step , col_start : col_end + 1: col_step]

default start is 0

default end is length of array

default step is 1 

each of the above is optional, except the first colon [:] 



mydata = np.array( [ [1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])
print(mydata)
print(mydata[:])  #all parameters left to default, will print full array , same as print(mydata)
print("\n\nOdd rows only \n{}\n".format(mydata[0::2]))
print("\n\nOdd columns only \n{}\n".format(mydata[:,0::2]))
print("\n\nEven rows and even columns \n{}\n".format(mydata[1::2,1::2]))
print("\n\nFirst two columns only \n{}\n".format(mydata[:,:2])) # [:,:2] => [:,0:2:1]
print("\n\nOnly second column of all rows\n{}\n".format(mydata[:,2])) #specific column
print("\n\nAll columns from second column onwards\n{}\n".format(mydata[:,2:])) # [:,:2] => [:,2:(len):1]
# note the difference between [:,2] and [:,2:] in above two cases

print("-------------------------Array Attributes----------------------")
#examine the array attributes
# Print out memory address
print("Memory Address: {} ".format(mydata.data))

# Print out the shape
print("Shape: {} ".format(mydata.shape))
# Print out the data type
print("Data Type: {} ".format(mydata.dtype))
# Print out the stride
print("Strides: {}".format(mydata.strides))
# Print the number of dimensions
print("Number of Dimensions: {}".format(mydata.ndim))

# Print the number of elements
print("Number of elements: {}".format(mydata.size))
# Print information about memory layout
print("Flags: {}".format(mydata.flags))
# Print the length of one array element in bytes
print("Size of single array element:{}".format(mydata.itemsize))
# Print the total consumed bytes by all elements
print("Total consumed bytes: {}".format(mydata.nbytes))






Output:

[[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12] [13 14 15 16]] [[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12] [13 14 15 16]] Odd rows only [[ 1 2 3 4] [ 9 10 11 12]] Odd columns only [[ 1 3] [ 5 7] [ 9 11] [13 15]] Even rows and even columns [[ 6 8] [14 16]] First two columns only [[ 1 2] [ 5 6] [ 9 10] [13 14]] Only second column of all rows [ 3 7 11 15] All columns from second column onwards [[ 3 4] [ 7 8] [11 12] [15 16]] -------------------------Array Attributes---------------------- Memory Address: <memory at 0x7fd113ace910> Shape: (4, 4) Data Type: int64 Strides: (32, 8) Number of Dimensions: 2 Number of elements: 16 Flags: C_CONTIGUOUS : True F_CONTIGUOUS : False OWNDATA : True WRITEABLE : True ALIGNED : True WRITEBACKIFCOPY : False UPDATEIFCOPY : False Size of single array element:8 Total consumed bytes: 128

No comments:

Post a Comment

How to check local and global angular versions

 Use the command ng version (or ng v ) to find the version of Angular CLI in the current folder. Run it outside of the Angular project, to f...