日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python?NumPy教程之數(shù)據類型對象詳解_python

作者:海擁 ? 更新時間: 2022-10-24 編程語言

每個 ndarray 都有一個關聯(lián)的數(shù)據類型 (dtype) 對象。這個數(shù)據類型對象(dtype)告訴我們數(shù)組的布局。這意味著它為我們提供了以下信息:

  • 數(shù)據類型(整數(shù)、浮點數(shù)、Python 對象等)
  • 數(shù)據大小(字節(jié)數(shù))
  • 數(shù)據的字節(jié)順序(小端或大端)
  • 如果數(shù)據類型是子數(shù)組,它的形狀和數(shù)據類型是什么。

ndarray 的值存儲在緩沖區(qū)中,可以將其視為連續(xù)的內存字節(jié)塊。所以這些字節(jié)將如何被解釋由dtype對象給出。 ?

構造數(shù)據類型(dtype)對象

數(shù)據類型對象是 numpy.dtype 類的一個實例,可以使用numpy.dtype.

參數(shù):

obj: 要轉換為數(shù)據類型對象的對象。

align?: [bool, optional] 向字段添加填充以匹配 C 編譯器為類似 C 結構輸出的內容。

copy?: [bool, optional] 制作數(shù)據類型對象的新副本。如果為 False,則結果可能只是對內置數(shù)據類型對象的引用。

# Python 程序創(chuàng)建數(shù)據類型對象
import numpy as np
 
# np.int16 被轉換為數(shù)據類型對象。
print(np.dtype(np.int16))

輸出:

int16

# Python 程序創(chuàng)建一個包含 32 位大端整數(shù)的數(shù)據類型對象
import numpy as np
 
# i4 表示大小為 4 字節(jié)的整數(shù)
# > 表示大端字節(jié)序和
# < 表示小端編碼。
# dt 是一個 dtype 對象
dt = np.dtype('>i4')
 
print("Byte order is:",dt.byteorder)
 
print("Size is:", dt.itemsize)
 
print("Data type is:", dt.name)

輸出:

Byte order is: >
Size is: 4
Name of data type is: int32

類型說明符(在上述情況下為 i4)可以采用不同的形式:

b1、i1、i2、i4、i8、u1、u2、u4、u8、f2、f4、f8、c8、c16、a(表示字節(jié)、整數(shù)、無符號整數(shù)、浮點數(shù)、指定字節(jié)長度的復數(shù)和定長字符串)

int8,...,uint8,...,float16, float32, float64, complex64, complex128(這次是大小)

注意: ?dtype 與 type 不同。

# 用于區(qū)分類型和數(shù)據類型的 Python 程序。
import numpy as np
 
a = np.array([1])
 
print("type is: ",type(a))
print("dtype is: ",a.dtype)

輸出:

type is: ? ?
dtype is: ?int32

具有結構化數(shù)組的數(shù)據類型對象

數(shù)據類型對象對于創(chuàng)建結構化數(shù)組很有用。結構化數(shù)組是包含不同類型數(shù)據的數(shù)組。可以借助字段訪問結構化數(shù)組。

字段就像為對象指定名稱。在結構化數(shù)組的情況下,dtype 對象也將是結構化的。

# 用于演示字段使用的 Python 程序
import numpy as np
 
# 一種結構化數(shù)據類型,包含一個 16 字符的字符串(在“name”字段中)和兩個 64 位浮點數(shù)的子數(shù)組(在“grades”字段中)
 
dt = np.dtype([('name', np.unicode_, 16),
               ('grades', np.float64, (2,))])
 
# 具有字段等級的對象的數(shù)據類型
print(dt['grades'])
 
# 具有字段名稱的對象的數(shù)據類型
print(dt['name'])

輸出:

('<f8', (2,))

# Python 程序演示了數(shù)據類型對象與結構化數(shù)組的使用。
import numpy as np
 
dt = np.dtype([('name', np.unicode_, 16),
               ('grades', np.float64, (2,))])
 
# x 是一個包含學生姓名和分數(shù)的結構化數(shù)組。
# 學生姓名的數(shù)據類型是np.unicode_,分數(shù)的數(shù)據類型是np.float(64)
x = np.array([('Sarah', (8.0, 7.0)),
              ('John', (6.0, 7.0))], dtype=dt)
 
print(x[1])
 
print("Grades of John are: ", x[1]['grades'])
print("Names are: ", x['name'])

輸出:

('John', [ 6., ?7.])
Grades of John are: ?[ 6. ?7.]
Names are: ?['Sarah' 'John']

原文鏈接:https://juejin.cn/post/7136106405836095525

欄目分類
最近更新