numpy之陣列建立

2022-01-22 14:28:26 字數 1805 閱讀 3889

#

coding=utf-8

import

numpy as np

import

random

############一維陣列建立#############

#方式一

t1 = np.array([1,2,3],dtype=float)

print

(t1,t1.dtype,t1.shape)

#方式二

t2 = np.array(range(5),dtype=float)

print

(t2,t2.dtype,t2.shape)

#方式三

t3 = np.arange(10).astype(float)

print

(t3,t3.dtype,t3.shape)

#方式四--->生成小數資料

t4 = np.array([random.random() for i in range(6)])

t4 = np.round(t4,2) #

round取兩位小數

print

(t4,t4.dtype,t4.shape)

#方式五 --->將多維矩陣轉為一維,將屬性行和列相乘

t = np.array([[1,2,3],[4,5,6]],dtype=float)

t = t.reshape((t.shape[1]*t.shape[0]))

print

(t,t.dtype,t.shape)

print("

*"*10)

#方式六(建議使用這種方式將多維轉為一維)

t = np.array([[1,2,3],[4,5,6]],dtype=float)

t =t.flatten()

print

(t,t.dtype,t.shape)

#############建立多維陣列##############

#方式一 --->建立全為0的3行4列矩陣

t5 = np.zeros((3,4),dtype=float)

print

(t5,t5.dtype,t5.shape)

#方式二 -->建立全為1的3行4列矩陣

t6 = np.ones((3,4),dtype=float)

print

(t6,t6.dtype,t6.shape)

#方式3 --->建立對角線為1的3行3列矩陣

t7 = np.eye(3)

print

(t7,t7.dtype,t7.shape)

#方式4 --->通過reshape()可以將一維或多維轉換其他維度矩陣

t8 = np.arange(10).reshape((2,5))

print

(t8,t8.dtype,t8.shape)

#方式五 --->通過random.randomint(start,end,size)

t = np.random.randint(3,12,(3,6))

print(t,t.shape)

#方式六 --->矩陣值都為6

a = np.full((2,3,4),6)

print(a)

#方式七 --->建立隨機矩陣

b = np.empty((3,4))

print(b)

'''多維陣列: (2,3,4):2表示兩塊資料,3表示一塊資料為3行,4表示一行資料為4列資料 注意只看reshape()最後兩位數,最前面的資料表示資料塊

'''

NumPy之ndarry陣列建立

numpy.empty方法 用來建立乙個指定形狀和型別的陣列,並且未初始化 numpy.empty shape,dtype float,order c 其中shape代表陣列形狀,dtype代表資料型別,order中 c 代表行優先 f 代表列優先。建立空陣列 x np.empty 3,2 dtyp...

NumPy 建立陣列

ndarray 陣列除了可以使用底層 ndarray 構造器來建立外,也可以通過以下幾種方式來建立。numpy.empty 方法用來建立乙個指定形狀 shape 資料型別 dtype 且未初始化的陣列 numpy.empty shape,dtype float,order c 引數說明 引數描述 s...

numpy建立陣列

numpy.empty 建立指定形狀 資料型別且未初始化的陣列 numpy.empty shape,dtype float,order c numpy.zeros 建立指定大小的全0陣列numpy.zeros shape,dtype float order c numpy.ones 建立指定大小的全...