當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python numpy.ndarray.view()用法及代碼示例


numpy.ndarray.view()有助於獲得具有相同數據的數組的新視圖。

用法: ndarray.view(dtype=None, type=None)

參數:
dtype:返回視圖的數據類型描述符,例如float32或int16。默認值為None(無),導致視圖具有與a相同的數據類型。
type:Python類型,可選


返回:ndarray或矩陣。

代碼1:

# Python program explaining   
# numpy.ndarray.view() function  
  
import numpy as geek 
  
a = geek.arange(10, dtype ='int16') 
  
print("a is:\n", a) 
  
# using view() method 
v = a.view('int32') 
print("\n After using view() with dtype = 'int32' a is:\n", a) 
  
v += 1
  
# addition of 1 to each element of v 
print("\n After using view() with dtype = 'int32' and adding 1 a is:\n", a)
輸出:
a is:
 [0 1 2 3 4 5 6 7 8 9]

 After using view() with dtype = 'int32' a is:
 [0 1 2 3 4 5 6 7 8 9]

 After using view() with dtype = 'int32' and adding 1 a is:
 [1 1 3 3 5 5 7 7 9 9]


代碼2:

# Python program explaining   
# numpy.ndarray.view() function  
  
import numpy as geek 
  
a = geek.arange(10, dtype ='int16') 
print("a is:", a) 
  
# Using view() method 
v = a.view('int16') 
print("\n After using view() with dtype = 'int16' a is:\n", a) 
  
v += 1
# addition of 1 to each element of v 
print("\n After using view() with dtype = 'int16' and adding 1 a is:\n", a)
輸出:
a is:[0 1 2 3 4 5 6 7 8 9]

 After using view() with dtype = 'int16' a is:
 [0 1 2 3 4 5 6 7 8 9]

 After using view() with dtype = 'int16' and adding 1 a is:
 [ 1  2  3  4  5  6  7  8  9 10]


代碼3:

# Python program explaining   
# numpy.ndarray.view() function  
  
import numpy as geek 
  
a = geek.arange(10, dtype ='int16') 
print("a is:\n", a) 
  
v = a.view('int8') 
print("\n After using view() with dtype = 'int8' a is:\n", a) 
  
v += 1
# addition of 1 to each element of v 
print("\n Ater using view() with dtype = 'int8' and adding 1 a is:\n", a)
輸出:
a is:
 [0 1 2 3 4 5 6 7 8 9]

 After using view() with dtype = 'int8' a is:
 [0 1 2 3 4 5 6 7 8 9]

 Ater using view() with dtype = 'int8' and adding 1 a is:
 [257 258 259 260 261 262 263 264 265 266]


相關用法


注:本文由純淨天空篩選整理自ArkadipGhosh大神的英文原創作品 numpy.ndarray.view() in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。