cheat-sheet-numpy-basics

The NumPy library is the core library for scientific computing in Python. It provides a high performance multidimensional array object, and tools for working with these arrays.

在这里插入图片描述

1. Creating Arrays

>>> a = np.array([1,2,3])
>>> b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
>>> c = np.array([[(1.5,2,3), (4,5,6)], [(3,2,1), (4,5,6)]], dtype = float)

1.1 Initial Placeholders

# Create an array of zeros
>>> np.zeros((3,4))

# Create an array of ones 
>>> np.ones((2,3,4),dtype=np.int16) 

# Create an array of evenly spaced values (step value) 
>>> d = np.arange(10,25,5) 

#  Create an array of evenly spaced values (number of samples)
>>> np.linspace(0,2,9)

# Create a constant array
>>> e = np.full((2,2),7) 

# Create a 2X2 identity matrix
>>> f = np.eye(2) 

# Create an array with random values
>>> np.random.random((2,2)) 

# Create an empty array
>>> np.empty((3,2))

2. Array Mathematics

2.1 Arithmetic Operations

>>> g = a - b # Subtraction
    array([[-0.5, 0. , 0. ], [-3. , -3. , -3. ]])
 
 
>>> np.subtract(a,b) # Subtraction
>>> b + a #  Addition
    array([[ 2.5, 4. , 6. ], [ 5. , 7. , 9. ]])

>>> np.add(b,a) # Addition
>>> a / b # Division
    array([[ 0.66666667, 1. , 1. ], [ 0.25 , 0.4 , 0.5 ]])

>>> np.divide(a,b) # Division
>>> a * b # Multiplication
 array([[ 1.5, 4. , 9. ], [ 4. , 10. , 18. ]])

>>> np.multiply(a,b) # Multiplication

>>> np.exp(b) # Exponentiation

>>> np.sqrt(b) # Square root

>>> np.sin(a) # Print sines of an array

>>> np.cos(b) # Element-wise cosine 

>>> np.log(a) # Element-wise natural logarithm
 
>>> e.dot(f) # Do product

2.2 Comparison

# Element-wise comparison
>>> a == b 
    array([[False, True, True], [False, False, False]], dtype=bool)

# Element-wise comparison
>>> a < 2 
    array([True, False, False], dtype=bool)

# Array-wise comparison
>>> np.array_equal(a, b) 

2.3 Aggregate Functions

>>> a.sum() # Array-wise sum
>>> a.min() # Array-wise minimum value 
>>> b.max(axis=0) # Maximum value of an array row
>>> b.cumsum(axis=1) # Cumulative sum of the elements
>>> a.mean() # Mean
>>> b.median() # Median
>>> a.corrcoef() # Correlation coefficien
>>> np.std(b) Standard deviation

3. Subsetting, Slicing, Indexing

3.1 Subsetting

>>> a[2] # Select the element at the 2nd index 3
    3

在这里插入图片描述

>>> b[1,2]#  Select the element at row 1 column 2 (equivalent to b[1][2])
      6.0

在这里插入图片描述

3.2 Slicing

# Select items at index 0 and 1
>>> a[0:2] 
    array([1, 2])

在这里插入图片描述

# Select items at rows 0 and 1 in column 1
>>> b[0:2,1]
    array([ 2., 5.])

在这里插入图片描述

# Select all items at row 0, (equivalent to b[0:1, :])
>>> b[:1] 
array([[1.5, 2., 3.]])

在这里插入图片描述

# Same as [1,:,:]
>>> c[1,...] 
    array([[[ 3., 2., 1.],
          [ 4., 5., 6.]]])
# Reversed array a
>>> a[ : :-1] 
     array([3, 2, 1])

3.3 Boolean Indexing

# Select elements from a less than 2
>>> a[a<2] 
    array([1])

在这里插入图片描述

3.4 Fancy Indexing

# Select elements (1,0),(0,1),(1,2) and (0,0)
>>> b[[1, 0, 1, 0],[0, 1, 2, 0]] 
    array([ 4. , 2. , 6. , 1.5])

# Select a subset of the matrix’s rows and columns
>>> b[[1, 0, 1, 0]][:,[0,1,2,0]] 
    array([[ 4. ,5. , 6. , 4. ], 
           [ 1.5, 2. , 3. , 1.5],
           [ 4. , 5. , 6. , 4. ],
           [ 1.5, 2. , 3. , 1.5]])

4. Array Manipulation

4.1 Transposing Array

>>> i = np.transpose(b) # Permute array dimensions
>>> i.T # Permute array dimensions

4.2 Changing Array Shape

>>> b.ravel() # Flatten the array
>>> g.reshape(3,-2) # Reshape, but don’t change data

4.3 Adding/Removing Elements

>>> h.resize((2,6)) # Return a new array with shape (2,6)
>>> np.append(h,g) # Append items to an array
>>> np.insert(a, 1, 5) # Insert items in an array
>>> np.delete(a,[1]) # Delete items from an array

4.4 Combining Arrays

# Concatenate arrays
>>> np.concatenate((a,d),axis=0) 
    array([ 1, 2, 3, 10, 15, 20])

# Stack arrays vertically (row-wise)
>>> np.vstack((a,b)) 
    array([[ 1. , 2. , 3. ],
          [ 1.5, 2. , 3. ],
          [ 4. , 5. , 6. ]])
# Stack arrays vertically (row-wise)      
>>> np.r_[e,f] 

# Stack arrays horizontally (column-wise)
>>> np.hstack((e,f)) 
    array([[ 7., 7., 1., 0.], 
          [ 7., 7., 0., 1.]])
        
# Create stacked column-wise arrays
>>> np.column_stack((a,d)) 
    array([[ 1, 10],
          [ 2, 15],
          [ 3, 20]])

# Create stacked column-wise arrays
>>> np.c_[a,d]

4.5 Splitting Arrays

# Split the array horizontally at the 3rd index
>>> np.hsplit(a,3) 
    [array([1]),array([2]),array([3])] 

# Split the array vertically at the 2nd index
>>> np.vsplit(c,2) 
    [array([[[ 1.5, 2. , 1. ],
            [ 4. , 5. , 6. ]]]), 
      array([[[ 3., 2., 3.],
            [ 4., 5., 6.]]])]

5. Other

5.1 I/O

# Saving & Loading On Disk
>>> np.save('my_array', a)
>>> np.savez('array.npz', a, b)
>>> np.load('my_array.npy')

# Saving & Loading Text Files
>>> np.loadtxt("myfile.txt")
>>> np.genfromtxt("my_file.csv", delimiter=',')
>>> np.savetxt("myarray.txt", a, delimiter=" ")

5.2 Data Types

>>> np.int64 # Signed 64-bit integer types
>>> np.float32 # Standard double-precision floating point
>>> np.complex # Complex numbers represented by 128 floats
>>> np.bool # Boolean type storing TRUE and FALSE values
>>> np.object # Python object type
>>> np.string_ # Fixed-length string type
>>> np.unicode_ # Fixed-length unicode type

5.3 Copy Arrays

>>> h = a.view() # Create a view of the array with the same data
>>> np.copy(a) # Create a copy of the array
>>> h = a.copy() # Create a deep copy of the array

5.4 Sorting Arrays

>>> a.sort() # Sort an array
>>> c.sort(axis=0) # Sort the elements of an array's axis

5.5 Inspecting Your Array

>>> a.shape # Array dimensions
>>> len(a) # Length of array
>>> b.ndim # Number of array dimensions
>>> e.size # Number of array elements
>>> b.dtype # Data type of array elements
>>> b.dtype.name # Name of data type
>>> b.astype(int) # Convert an array to a different type

5.6 Asking for Help

>>> np.info(np.ndarray.dtype)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值