NumPy Array Base Operations-indexing, grouping, partitioning, copying, traversal, transformation, serialization (iv)

Source: Internet
Author: User
Tags object serialization serialization

numpy Array Base Operation


1. Array index Access

#!/usr/bin/env python  
# encoding:utf-8  

import numpy as np

B = Np.array ([[1,2,3],[4,5,6],[7,8,9],[10,11,12 ]],dtype=int)

C = b[0,1]  #1行 Second cell element
# output: 2

d = b[:,1]  #所有行 Second cell element
# output: [2  5  8 11]< C13/>e = b[1,:]  #2行 All cell elements
# output: [4 5 6]

f = b[1,1:]  all elements # output after the start of the 2nd unit
: [5 6]

g = b[1,: 2]  #2行 unit 1th starts with all elements of the index of 2 before the
# output: [4 5]

2. Array of combinations (functions)

'''
# combination function
#创建两个测试数组
# Arange creates a one-dimensional one with 9 elements
# reshape method, you can create a new array that changes the size, and the shape of the original array remains the same:
# here Reshape (3,3) will generate a 3-dimensional array of 3 elements as a group
'''

#创建两个测试数组
A = Np.arange (9). Reshape (3,3)  
'
 Array ([[0, 1, 2], [3, 4, 5], [6, 7, 8]  
           ]) ' '
b = 2 * A
' '
array ([[0, 2, 4],  
       [6, 8, ten], [A, b]  
       ])  


#水平组合

Np.hstack ((A, b)) 
'
Array ([[0, 1, 2, 0, 2, 4],  
       [3, 4, 5, 6, 8, ten],  
       [6, 7, 8,]] 
'

#通过concatenate函数并指定相应的轴 (Axis=1 level, axis=0 vertical)
con = Np.concatenate ((A, B), Axis=1)
'
Array ( [[0, 1, 2, 0, 2, 4],  
       [3, 4, 5, 6, 8, ten],  
       [6, 7, 8,,,]]]  

#垂直组合

Np.vstack ((A, b))
'
Array ([[0, 1, 2],  
       [3, 4, 5], [  
       6, 7  
       , 8], [0, 2, 4], [6,,] [8, 12], ] "
#或者使用concatenate 
con = np.concatenate ((A, B), axis=0)

#深度组合 Dstack (that is, the combination of the third axis (that is, the depth) of the array to generate a new list of arrays)
Np.dstack ((A, b))  
' Array ([[[
0, 0],  
        [1, 2],  
        [2, 4]], [[3, 6], [4, 8], [  
        5, 10]],  
  
       [[6],  
        [7],  
        [8,]]]  

"

#行组合, a row combination can combine multiple one-dimensional arrays as each row of the new array
#对于2维数组, it works just like a vertical combination.

one = Np.arange (2)
' '
array ([0, 1])
' '

two = one + 2 
'
Array ([2, 3])

' Np.row_stack ((one, two))
'

Array ([[0, 1],  
       [2, 3]]) 
'

#列组合 (for a 2-d array, it acts like a horizontal combination.) )

Np.column_stack ((oned, twiceoned))  
'
Array ([[0, 2],  
       [1, 3]])  
'


3. Array segmentation

In NumPy, the functions of the split array are hsplit, Vsplit, Dsplit, and split. You can split an array into a child array of the same size, or specify the location of the original array split.

#水平分割

A = Arange (9). Reshape (3,3) 
'
Array ([[0, 1, 2],  
       [3, 4, 5], [6, 7, 8]  
       ]) 
'

np.hsplit (A, 3) c13/> ' [[
0],  
       [3], [  
       6]]), Array ([  
 [1],  
       [4],  
       [7]]), Array ([  
 [2],  
       [5],  
       [8]]] 

"
#方法二: Use the Split function and specify an axis of 1
np.split (A, 3, Axis=1)  


#垂直分割
#垂直分割是沿着垂直的轴切分数组:

Np.vsplit (A, 3)  
'
[Array ([[0, 1, 2]]), Array ([[3, 4, 5]]), Array ([[6, 7, 8]])] "

#方法二
Solit function and specifies that the axis is 1
np.split (A, 3, axis=0)

#面向深度的分割
#dsplit函数使用的是面向深度的分割

c = Arange. Reshape (3, 3, 3) ' Array ([[[[0, 1, 2  ],  
        [3, 4, 5  ],  
        [  6, 7, 8] ]], [[9, one], [A, M], [a]], [[A, M], [From, To, [  
        24,  
        25, 26]]]  

'

np.dsplit (c, 3) 
'
[Array ([[[0],  
        [3],  
        [6]],  
  
       [[9],  
        [a],  
        [15] ], [[[], [], [[]]], Array ([[[[  
 1],  
        [4],  
        [7]],  
  
       [[  
        ], [[]], [16 ]], [[[], [], []], Array ([[[  
 2],  
        [5], [  
        8]],  
  
       [[one], [  
        a  
        ], [ ]], [[m],  
        [G],  
        [  
]]]


4. To determine whether the array is shared memory, is also used to directly determine the data is copied or mirrored

#方法一:
a = np.arange
B = A.reshape ((5))
print (B.base is a)

#方法二:
print (np.may_share_memory (A, B))

#方法三:
print (b.flags[' owndata '])  #False--apparently is a view
e = Np.ravel (b[:, 2])
print (E.fla gs[' Owndata ']  #True--apparently is a new NumPy object.

5. Array replication and mirroring (view)

1.) do not replicate at all, simply assign values without duplicating array objects or their data.

A = Np.arange (a)  
B = A      #不创建新对象  
B is a     # A and B are the two names of the same array objects
#  true
    
b.shape = 3,4    #也改变了a的形状 
print A.shape '
(3, 4)
'

2. View's usage views method creates a new array object that points to the same data.

In fact, no data type is fixed, depending on how the memory area of the piece of data is viewed.
In Numpy.ndarray.view, it provides a different way of cutting the memory area to complete the conversion of data types without having to do additional copy of the data to save memory space.

c = A.view ()  
C is a  
# false

c.base is a      #c是a持有数据的镜像 
#true

c.shape = 2,6    # A has not changed the shape of
print (a . Shape)  # (3, 4) 

c[0,4] = 1234        #a的数据改变了
print  a
' '
array ([[   0,    1,    2,    3],  
       [1234,    5,    6,    7],  
       [   8,    9, one   ]]]

3.) Slice array returns one of its views

s = a[:, 1:3]     # Gets the elements of 1, 2 for each row
s[:] =           # s[:] is a mirror image of S. Note the difference between s=10 and s[:]=10 
print a
' '
array ([[   0, ten,    3],  
       [1234,   10,    7],  
       [   8,   Ten, one   ]]  
"

4.) deep copy, this replication method completely copies the array and its data.

D = a.copy ()       #创建了一个含有新数据的新数组对象
D is a
#False

d.base is a        #d和a现在没有任何关系
#False  

d[0,0] = 9999
print a
'
array ([[0,   Ten,    3],  
       [1234,   Ten,    7],  
       [   8,   Ten, one   ]] 
"

5.) Application in image processing

When you need to do the same processing for three channels of an input image, Using Cv2.split and Cv2.merge is a waste of resources because the data for any one channel is the same for processing, and we can use the view to convert it to a one-dimensional matrix and then do the processing, which requires no additional memory overhead and time overhead.

def createflatview (array): "" "return a 1D view of the An array of the any  
    dimensionality.  
    " " Flatview = Array.view ()  
    flatview.shape = array.size return  
    Flatview  


5. Array traversal

A = Np.arange (9). Reshape (3,3) for 
row in a:
  print row 
' '
[0 1 2]
[3 4 5]
[6 7 8] '

#对数组 You can use the Flat property, which is an array element iterator: For the element in
A.flat:
  print element
'
0 1 2 3 4
5 6 7 8 '

6. Data type conversion

Np.float64 float64
#42.0

np.int8 (42.0)  # to int8
#42

Np.bool (a) to   bool
#True  

np.bool (42.0)  # to bool
#True  

np.float (True)  # to float
#1.0 


# You can specify the type of the parameter in the parameter of the function
Arange (7, dtype=uint16)  
    Array ([0, 1, 2, 3, 4, 5, 6], dtype=uint16)

6. Array serialization and deserialization

Serialization is the process of converting an object's state into a form that can be persisted or transmitted. The serialized complement is deserialized, which converts the stream to an object. Together, these two processes ensure that data is easy to store and transmit.

Python provides pickle, Cpickle object serialization/deserialization

This uses the functions provided by NumPy

#预定义数据栏位名称和类型  
table = np.loadtxt (' example.txt ', dtype= ' names ': (' ID ', ' result ', ' Type '), \  
    ' formats ': (' S4 ', ' F4 ', ' i2 ')  
np.savetxt (' somenewfile.txt ') #序列化  
#二进制文件加载, save  
data = Np.empty ((1000, 1000))  
Np.save (' Test.npy ', data]  
Np.savez (' Test.npz ', data) #采用压缩  
NewData = np.load (' test.npy ')   

7. Minimum value of maximum value in array

Mat.max (0) #n维数组axis = minimum value of 0 dimension, maximum value  



Reference and reprint:

http://blog.csdn.net/sunny2038/article/details/8907736


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.