当前位置:网站首页>Notes | numpy-11 Array operation
Notes | numpy-11 Array operation
2022-07-03 04:49:00 【CY3761】
#%%
# Used to process arrays , It can be divided into the following categories
""" Modify array shape Flip array Modify array dimensions Linked array Split array Addition and deletion of array elements """
#%% md
## Modify array shape
#%%
""" function describe reshape Modify the shape without changing the data flat Array element iterator flatten Returns a copy of the array , Changes made to the copy do not affect the original array ravel Return expanded array """
#%% md
### numpy.reshape
numpy.reshape Function can change shape without changing data
#%%
# numpy.reshape(arr, newshape, order='C')
""" arr: Array of shapes to modify newshape: Integers or arrays of integers , The new shape should be compatible with the original shape order:'C' -- Press the line ,'F' -- By column ,'A' -- The original order ,'k' -- The order in which elements appear in memory """
#%%
import numpy as np
a = np.arange(8)
a
#%%
b = a.reshape(4,2) # 4r2c
b
#%% md
### numpy.ndarray.flat
numpy.ndarray.flat Is an array element iterator
#%%
import numpy as np
a = np.arange(9).reshape(3, 3)
a
#%%
for _ in a: # Traversal Not iterative traversal
print(_) # Each line of data
#%%
# Iterate through
for _ in a.flat:
print(_, end=', ') # Every element In line order
#%% md
### numpy.ndarray.flatten
numpy.ndarray.flatten Returns a copy of the array , Changes made to the copy do not affect the original array
#%%
# ndarray.flatten(order='C')
""" order:'C' -- Press the line ,'F' -- By column ,'A' -- The original order ,'K' -- The order in which elements appear in memory """
#%%
import numpy as np
a = np.arange(8).reshape(2, 4)
a
#%%
a.flatten() # Expand the array nr1c | level
#%%
a.flatten(order='F') # With F style ( vertical ) Expand the array ( New array )
#%% md
### numpy.ravel
numpy.ravel() Flattened array elements , The order is usually "C style ", The return is the array view (view, It's kind of similar C/C++ quote reference The mean of ), The modification will affect the original array
#%%
# numpy.ravel(a, order='C')
""" order:'C' -- Press the line ,'F' -- By column ,'A' -- The original order ,'K' -- The order in which elements appear in memory """
#%%
import numpy as np
a = np.arange(8).reshape(2, 4)
a
#%%
a.ravel() # Also expand the array | level
#%%
a.ravel(order='F') # vertical
#%% md
## Flip array
#%%
""" function describe transpose Change the dimensions of an array ndarray.T and self.transpose() identical rollaxis Scroll back the specified axis swapaxes Swap the two axes of the array """
#%%
# numpy.transpose
# numpy.transpose Function is used to change the dimensions of an array
""" numpy.transpose(arr, axes) arr: Array to operate axes: List of integers , Corresponding dimension , Usually all dimensions change """
#%%
import numpy as np
a = np.arange(12).reshape(3, 4)
a
#%%
np.transpose(a)
#%%
a.T
#%% md
### numpy.rollaxis
numpy.rollaxis Function to scroll back a specific axis to a specific position
#%%
# numpy.rollaxis(arr, axis, start) | Hard to understand
""" arr: Array axis: The axis to roll back , The relative position of the other axes will not change start: Default to zero , Indicates complete scrolling . Will scroll to a specific location """
#%%
import numpy as np
# Three dimensional array
a = np.arange(8).reshape((2, 2, 2)) # 2 Group 2 That's ok 2 Column
a[0]
#%%
a[1]
#%%
# Get one of the values
print(np.where(a==6)) # Return index coordinates
a[1,1,0] # Different dimension processing uses , The same dimension processing uses :
#%%
# Place the shaft 2 Scroll to the axis 0( Width to depth )
""" Group row and column b0 000=0 010=2 100=4 110=6 b1 001=1 011=3 101=5 111=7 """
b = np.rollaxis(a, 2, 0) #
b[0]
#%%
b[1]
#%%
# Place the shaft 2 Scroll to the axis 1 ( Width to height )
""" Group row and column c0 000=0 010=2 001=1 011=3 c1 100=4 110=6 101=5 111=7 """
c = np.rollaxis(a, 2, 1) # Horizontal take Place vertically
c[0]
#%%
c[1]
#%%
np.where(c==6)
#%% md
### numpy.swapaxes
numpy.swapaxes Function to exchange two axes of an array
#%%
# numpy.swapaxes(arr, axis1, axis2)
""" arr: Input array axis1: The integer corresponding to the first axis axis2: The integer corresponding to the second axis """
#%%
import numpy as np
a = np.arange(8).reshape(2,2,2)
a[0]
#%%
a[1]
#%%
# Now swap the axes 0( Depth direction ) To shaft 2( Width direction )
b = np.swapaxes(a, 2, 0) # This similar level of processing
b[0]
#%%
b[1]
#%%
# rollaxis and swapaxes ( Follow up research )
# https://zhuanlan.zhihu.com/p/162874970
#%% md
## Modify array dimensions
#%%
""" dimension describe broadcast Generate an object that mimics the broadcast broadcast_to Broadcast array to new shape expand_dims Expand the shape of the array squeeze Remove one-dimensional entries from the shape of the array """
#%%
# numpy.broadcast
# numpy.broadcast Object used to imitate broadcast , It returns an object , This object encapsulates the result of broadcasting one array to another
#%%
import numpy as np
x = np.array([
[1],
[2],
[3]
])
x
#%%
y = np.array([4, 5, 6])
y
#%%
b = np.broadcast(x, y) # Yes y radio broadcast x
r,c = b.iters
b, r, c, b.shape # The shape of the broadcast object
#%%
while True:
try:
print('x=%d, y=%d' % (next(r), next(c)))
except (Exception, BaseException):
break
#%%
b = np.broadcast(x, y)
c = np.empty(b.shape)
print(c.shape)
c
#%%
c.flat = [u + v for (u, v) in b] # To add
c
#%%
# Got and NumPy The built-in broadcast supports the same results
x + y
#%% md
### numpy.broadcast_to
numpy.broadcast_to Function to broadcast an array to a new shape . It returns a read-only view on the original array . It is usually discontinuous . If the new shape doesn't fit NumPy The broadcast rules of , This function may throw ValueError
#%%
# numpy.broadcast_to(array, shape, subok)
#%%
import numpy as np
a = np.arange(4).reshape((1, 4))
a
#%%
np.broadcast_to(a, (4, 4)) # Broadcast for 4r4c
#%% md
### numpy.expand_dims
numpy.expand_dims Function expands the array shape by inserting a new axis at the specified position
#%%
# numpy.expand_dims(arr, axis)
""" arr: Input array axis: Where the new shaft is inserted """
#%%
import numpy as np
x = np.array((
[1, 2],
[3, 4]
))
x
#%%
y = np.expand_dims(x, axis=0) # change 3 dimension
y
#%%
x.ndim, y.ndim, x.shape, y.shape
#%% md
### numpy.squeeze
numpy.squeeze Function deletes a one-dimensional entry from the shape of a given array
#%%
# numpy.squeeze(arr, axis)
""" arr: Input array axis: Integer or integer tuple , Used to select a subset of one-dimensional entries in the shape """
#%%
import numpy as np
x = np.arange(9).reshape((1, 3, 3))
x
#%%
y = np.squeeze(x) # Delete one dimension The outermost layer of the original array should only have 1 layer
y
#%%
x.shape, y.shape
#%% md
## Linked array
#%%
""" function describe concatenate Join the array sequence along the existing axis stack Add a series of arrays along the new axis . hstack Stack arrays in a sequence horizontally ( Column direction ) vstack Stack arrays in a sequence vertically ( Line direction ) """
#%% md
### numpy.concatenate
#%%
# numpy.concatenate((a1, a2, ...), axis)
""" a1, a2, ...: Arrays of the same type axis: Along the axis that it joins the array , The default is 0 """
#%%
import numpy as np
a = np.array([
[1, 2],
[3, 4]
])
a
#%%
b = np.array([
[5, 6],
[7, 8]
])
b
#%%
np.concatenate((a, b)) # Along 0 Shaft connection Vertical connection
#%%
np.concatenate((a, b), axis=1) # Along axis 1 Concatenate two arrays Horizontal connection
#%% md
### numpy.stack
numpy.stack Function to join an array sequence along a new axis
#%%
# numpy.stack(arrays, axis)
""" arrays Array sequence of the same shape axis: Returns the axis in the array , Input arrays are stacked along it """
#%%
import numpy as np
a = np.array([
[1, 2],
[3, 4]
])
a
#%%
b = np.array([
[5, 6],
[7, 8]
])
b
#%%
np.stack((a, b), 0) # Along axis 0 Stack two arrays | Become three-dimensional a b Each group
#%%
np.stack((a, b), 1) # Along axis 1 Stack two arrays | Become three-dimensional a And b Mix together Place vertically
#%% md
### numpy.hstack
numpy.hstack yes numpy.stack Variations of functions , It generates arrays by stacking them horizontally
#%%
import numpy as np
np.hstack((a, b)) # level
#%% md
### numpy.vstack
numpy.vstack yes numpy.stack Variations of functions , It generates arrays by stacking vertically
#%%
import numpy as np
np.vstack((a, b)) # vertical
#%% md
## Split array
#%%
""" function Array and operation split Divide an array into multiple subarrays hsplit Divide an array horizontally into multiple subarrays ( By column ) vsplit Divide an array vertically into multiple subarrays ( Press the line ) """
#%% md
### numpy.split
numpy.split The function splits an array into subarrays along a specific axis
#%%
# numpy.split(ary, indices_or_sections, axis)
""" ary: Split array indices_or_sections: If it's an integer , Just use this number to average the segmentation , If it's an array , Is the location of the cut along the axis ( Left open right closed ) axis: Set the direction along which to slice , The default is 0, Transverse segmentation , That is, the horizontal direction . by 1 when , Vertical segmentation , Vertical direction """
#%%
import numpy as np
a = np.arange(9)
a
#%%
b = np.split(a, 3) # It is divided into three sub arrays of equal size
b
#%%
b = np.split(a, [4, 7])# Divide the position indicated in the one-dimensional array | Take the previous one
b
#%%
# axis by 0 Split horizontally ,axis by 1 Split in the vertical direction
import numpy as np
a = np.arange(16).reshape(4, 4)
a
#%%
np.split(a, 2) # Default split (0 Axis ) | level The whole is divided into two parts 2 That's ok
#%%
np.split(a, 2, 1) # vertical Divide into various 2 Column
#%%
np.hsplit(a, 2) # various 2 Column
#%% md
### numpy.hsplit
#%%
# numpy.hsplit Function to split an array horizontally , Split the original array by specifying the number of arrays of the same shape to return
harr = np.floor(10 * np.random.random((2, 6))) # random number * 10 Rounding down
harr
#%%
np.hsplit(harr, 3) # branch 3 Column 01, 23, 45 Horizontal is vertical , Left to right
#%% md
### numpy.vsplit
#%%
# numpy.vsplit Divide along the vertical axis , It's divided in the way of hsplit The usage is the same
np.vsplit(harr, 2) # branch 2 That's ok 0,1 Vertical is horizontal , Up and down
#%% md
## Addition and deletion of array elements
#%%
""" function Elements and descriptions resize Returns a new array of specified shapes append Add values to the end of the array insert Inserts a value along the specified axis before the specified subscript delete Delete the subarray of a certain axis , And return the new array after deletion unique Find the only element in the array """
#%% md
### numpy.resize
numpy.resize Function returns a new array of the specified size .
If the new array size is larger than the original size , Contains a copy of the elements in the original array
#%%
import numpy as np
a = np.array([
[1, 2, 3],
[4, 5, 6]
])
a
#%%
a.shape
#%%
b = np.resize(a, (3, 2)) # It's kind of similar reshape
b
#%%
b.shape
#%%
b = np.resize(a, (3, 3)) # it is to be noted that a The first line of is b Repeated in , Because the size has become larger This is not like reshape 了
b
#%% md
### numpy.append
numpy.append Function to add a value to the end of the array . The append operation allocates the entire array , And copy the original array into the new array . Besides , The dimensions of the input array must match, otherwise ValueError.|
#%%
# numpy.append(arr, values, axis=None)
""" arr: Input array values: Want to arr Added value , Need and arr The same shape ( Except for the axis to be added ) axis: The default is None. When axis When there is no definition , It's a horizontal bonus , The return is always a one-dimensional array ! When axis When there is a definition , Respectively 0 and 1 When . When axis When there is a definition , Respectively 0 and 1 When ( The number of columns should be the same ). When axis by 1 when , The array is added to the right ( The number of lines should be the same ). """
#%%
import numpy as np
a = np.array([
[1, 2, 3],
[4, 5, 6]
])
a
#%%
np.append(a, [7, 8, 9]) # Add elements to the array
#%%
np.append(a, [[7, 8, 9]], axis=0) # Add down
#%%
np.append(a, [[5,5,5],[7, 8, 9]], axis=1) # Append to the right
#%% md
### numpy.insert
numpy.insert Function before the given index , Inserts a value in the input array along a given axis .
If the type of the value is converted to be inserted , Then it is different from the input array . Insert... Without in place , The function returns a new array . Besides , If no shaft is provided , Then the input array will be expanded
#%%
import numpy as np
a = np.array([
[1,2],
[3,4],
[5, 6]
])
a
#%%
np.insert(a, 3, [11,12]) # Not delivered Axis Parameters . Before deleting, the input array will be expanded | First turn to one dimension Then insert
#%%
# Pass the Axis Parameters . Can broadcast value array to match input array
np.insert(a, 1, [11], axis=0) # Pass the Axis Parameters . Can broadcast value array to match input array | 1 Here refers to the index of the row
#%%
np.insert(a, 1, [11], axis=1) # 1 Here refers to the index of the column
#%% md
### numpy.delete
numpy.delete Function returns a new array that removes the specified subarray from the input array . And insert() The same is true for functions , If no axis parameters are provided , The input array will expand
#%%
# Numpy.delete(arr, obj, axis)
""" arr: Input array obj: Can be sliced , Integers or arrays of integers , Indicates the subarray to be removed from the input array axis: Along the axis it removes the given subarray , If not provided , Then the input array will be expanded """
#%%
import numpy as np
a = np.arange(12).reshape((3, 4))
a
#%%
# Not delivered Axis Parameters . The input array will be expanded before insertion
np.delete(a, 5) # Indexes 5 The element of is gone Later, modify it forward
#%%
np.delete(a, 1, axis=0) # Delete the second line Row index 1 4567 be without
#%%
np.delete(a, 1, axis=1) # Delete the second column Column index 1 159 be without
#%%
# A slice containing alternative values removed from an array
a = np.arange(1, 11)
a
#%%
np.delete(a, np.s_[::2]) # step 2 Reservations Delete the rest
#%% md
### numpy.unique
numpy.unique Function to remove duplicate elements from an array
#%%
# numpy.unique(arr, return_index, return_inverse, return_counts)
""" arr: Input array , If it is not a one-dimensional array, it will expand return_index: If true, Returns the location of the new list element in the old list ( Subscript ), And in the form of lists return_inverse: If true, Returns the position of the old list element in the new list ( Subscript ), And in the form of lists return_counts: If true, Returns the number of occurrences of elements in the de duplicated array in the original array """
#%%
import numpy as np
a = np.array([5,2,6,2,7,6,8,2,9])
a
#%%
u = np.unique(a) # What is returned is not repeated
u
#%%
u, indices = np.unique(a, return_index=True) # Index array of de duplication array
u
#%%
indices # Index of non repeating elements
#%%
a[indices] # Reconstruct the original array with subscripts
#%%
# Returns the number of repetitions of de heavy elements
u, indices = np.unique(a, return_counts=True)
u
#%%
a
#%%
indices # Returns the number of repetitions of de heavy elements
#%%
边栏推荐
- 有道云笔记
- Golang -- realize file transfer
- LVS load balancing cluster of efficient multi-purpose cluster (NAT mode)
- Current market situation and development prospect forecast of the global fire boots industry in 2022
- On typescript and grammar
- [USACO 2009 Dec S]Music Notes
- Review the old and know the new: Notes on Data Science
- MPM model and ab pressure test
- JVM原理简介
- 2022 a special equipment related management (elevator) analysis and a special equipment related management (elevator) simulation test
猜你喜欢

MediaTek 2023 IC written examination approved in advance (topic)

Number of uniform strings of leetcode simple problem

First + only! Alibaba cloud's real-time computing version of Flink passed the stability test of big data products of the Institute of ICT

I've been in software testing for 8 years and worked as a test leader for 3 years. I can also be a programmer if I'm not a professional
![[luatos sensor] 1 light sensing bh1750](/img/70/07f29e072c0b8630f92ec837fc12d5.jpg)
[luatos sensor] 1 light sensing bh1750

After job hopping at the end of the year, I interviewed more than 30 companies in two weeks and finally landed

2022 tea master (intermediate) examination questions and tea master (intermediate) examination skills

【XSS绕过-防护策略】理解防护策略,更好的绕过

I stepped on a foundation pit today

Symbol of array element product of leetcode simple problem
随机推荐
Flutter monitors volume to realize waveform visualization of audio
Market status and development prospect prediction of global fermented plant protein industry in 2022
I've seen a piece of code in the past. I don't know what I'm doing. I can review it when I have time
Number of 1 in binary (simple difficulty)
4 years of experience to interview test development, 10 minutes to end, ask too
[set theory] binary relation (example of binary relation on a | binary relation on a)
Leetcode simple question: check whether the array is sorted and rotated
[set theory] binary relation (example of binary relation operation | example of inverse operation | example of composite operation | example of limiting operation | example of image operation)
Matplotlib -- save graph
Leetcode simple question: check whether the string is an array prefix
Sdl2 + OpenGL glsl practice (Continued)
【SQL注入点】注入点出现位置、判断
String matching: find a substring in a string
Introduction to JVM principle
[set theory] binary relationship (binary relationship notation | binary relationship from a to B | number of binary relationships | example of binary relationship)
[luatos sensor] 1 light sensing bh1750
[XSS bypass - protection strategy] understand the protection strategy and better bypass
stm32逆向入门
The programmer went to bed at 12 o'clock in the middle of the night, and the leader angrily scolded: go to bed so early, you are very good at keeping fit
The least operation of leetcode simple problem makes the array increment