In [1]:
import numpy as np
data = [2,4,1.2,34,0]
# 基本类型数组
array = np.array(data)
print(array)
# 嵌套类型数组
data_qt = [[1,3,5,7],[2,4,6,8]]
array_qt = np.array(data_qt)
print(array_qt)
print(array_qt.ndim,array_qt.shape)
…
In [7]:
print(array.dtype) # 数据类型
print(array_qt.dtype)
…
In [ ]:
## zeros和ones可以创建指定长度或维度的全0或全1数组。
## empty可以创建一个没有任何具体值得数组。
…
In [23]:
zero = np.zeros((3,5)) # 创建3*5的二维数组,内容全为0
print(zero)
print("*"*70)
empty = np.empty((2,3,4)) # 随机生成2块,3行,4列数据
print(empty)
…
In [ ]:
## ndarray的数据类型
…
In [24]:
print(np.array([1,2,3],dtype=np.float64))
print(np.array([1,2,3],dtype=np.int32))
…
In [25]:
print(array[1:3])
…
In [27]:
num = np.random.randn(3,2)
num_t = num.T
num_dot_t = np.dot(num,num_t)
print(num)
print("*"*50)
print(num_t)
print("*"*50)
print(num_dot_t)
…
In [12]:
points = np.arange(-5, 5, 0.01) #创建numpy数组,从-5~5,步长为0.01,共1000个数据
xs, ys = np.meshgrid(points, points) # np.meshgrid(arg1, arg2)函数接收两个一维数组,返回二维矩阵
import matplotlib.pyplot as plt
z = np.sqrt(xs ** 2 + ys ** 2)
plt.imshow(z, cmap=plt.cm.gray)
plt.colorbar()
plt.title("Image plot of :\n{}".format(z))
print("矩阵乘积:\n{}".format(z))
…
In [15]:
xarr = np.array([1.1, 1.2, 1.3, 1.4, 1.5])
yarr = np.array([2.1, 2.2, 2.3, 2.4, 2.5])
cond = np.array([True, False, True, True, False])
# 根据cond的值进行选择,如果为True则保留xarr的值,否则保留yarr的值
result = [(x if c else y)for x, y, c in zip(xarr, yarr, cond)]
# 使用where
result_where = np.where(cond, xarr, yarr)
print("基于if:\n{}".format(result))
print("基于where:\n{}".format(result_where))
print("{},{}".format(result[0], result_where[0]))
…
In [24]:
arr = np.random.randn(4, 4)
# arr_demo = np.random.randn(5, 4)
print(arr)
print("="*60)
arr_new = np.where(arr > 0, 6, -6) # 正值设置为6负值设置为-6
arr_new_arr = np.where(arr > 0, 6, arr) # 只将正值设置为6
print("{}\n{}".format(arr_new, arr_new_arr))
[-0.66935063 -0.82916227 1.07172145 0.5246802 ]]
[[-6 6 6 6]
[-6 6 -6 6]
[ 6 6 6 -6]
[-6 -6 6 6]]
[[-1.07154786 6. 6. 6. ]
[-1.04776947 6. -0.09888813 6. ]
[ 6. 6. 6. -0.4545642 ]
[-0.66935063 -0.82916227 6. 6. ]]
…
In [26]:
bools = np.array([False, False, True, False])
bool_any = bools.any()
bool_all = bools.all()
print("{}\n{}".format(bool_any, bool_all))
…
In [27]:
names = np.array(['Bob','Joe','Michial','Bob','Joe','Joe'])
ints = np.array([3, 2, 4, 2, 2, 3, 5, 3])
names_unique = np.unique(names)
ints_unique = np.unique(ints)
print("{}\n{}".format(names_unique,ints_unique))
…
In [28]:
values = np.array([3, 4, 2, 3, 1, 2])
if_contains_values = np.in1d(values, [1, 3, 5])
print(if_contains_values)
…
In [ ]:
…