Python uses numpy module to realize the connection operation method between matrix and list

  • 2021-07-03 00:24:08
  • OfStack

Numpy module is widely used in scientific and numerical calculation, Naturally, it has its powerful points. Before, when data list or matrix splicing was needed in feature processing, it was completed by my own functions. Today, I found a fun function, which is not only fun, but also has powerful key performance, that is, the matrix and list connection function of Numpy module. Practice 1.


#!usr/bin/env python
#encoding:utf-8
from __future__ import division
 
'''
__Author__: Yishui Cold City 
 Use numpy Module realizes the connection operation of matrix 
'''
 
import numpy as np
 
def simple_test():
  '''
   A simple little experiment 
  '''
  sim_one,sim_two=[1,5,8,0,3,6],[11,5,8,0,3]
  one_list=[[1,2,3],[1,2,1],[3,4,5],[4,5,6]]
  two_list=[[5,6,7],[6,7,8],[6,7,9],[0,4,7],[4,6,0],[2,9,1],[5,8,7],[9,7,8],[3,7,9]]
  three_list=[[0,4,3,7],[4,6,1,0],[2,5,9,1]]
  three_list=np.array(three_list)
  four_list=[[2,9,1],[5,8,7],[9,7,8],[3,7,9]]
  print ' Right 1 The result of dimension list connection is: '
  pring np.concatenate([sim_one,sim_two],axis=0)
  print ' Connecting two matrices by row results in: '
  print np.concatenate([one_list,two_list],axis=0)
  print ' Connecting two matrices by column results in: '
  print np.concatenate([one_list,three_list.T],axis=1)
  print np.concatenate([one_list,four_list],axis=1)
 
 
if __name__ == '__main__':
  simple_test()

The results are as follows:


[Decode error - output not utf-8]
[Decode error - output not utf-8]
[ 1 5 8 0 3 6 11 5 8 0 3]
 Connecting two matrices by row results in: 
[[1 2 3]
 [1 2 1]
 [3 4 5]
 [4 5 6]
 [5 6 7]
 [6 7 8]
 [6 7 9]
 [0 4 7]
 [4 6 0]
 [2 9 1]
 [5 8 7]
 [9 7 8]
 [3 7 9]]
 Connecting two matrices by column results in: 
[[1 2 3 0 4 2]
 [1 2 1 4 6 5]
 [3 4 5 3 1 9]
 [4 5 6 7 0 1]]
[[1 2 3 2 9 1]
 [1 2 1 5 8 7]
 [3 4 5 9 7 8]
 [4 5 6 3 7 9]]
[Finished in 0.5s]

In the np. concatenate () function, the first parameter is the matrix and list to be merged, and the second parameter is 0 to indicate that the data is connected by rows, and 1 to indicate that the data is connected by columns.

From the above results, we can see that axis parameter can be omitted for 1-D list, and axis parameter can also be omitted for 2-D list when axis is 0

When axis is 1, it should be noted that the number of rows and columns of the connected data matrix needs to be the same, otherwise an error will be reported:


AttributeError: 'list' object has no attribute 'T'

That is, when axis is 1, it is essentially enough to directly connect the data of the corresponding rows of the matrix based on the behavior reference

When axis is 1, it is essentially enough to base the matrix on columns and stack the data down from 1


Related articles: