記錄一下基本功的練習(xí)
截屏2020-08-31上午8.43.29.png
練習(xí)代碼
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
np.random.seed(0)
# 配置pandas顯示
pd.set_option('display.max_rows', 10)
pd.set_option('display.max_columns', 10)
data = np.random.rand(2, 3)
print(data)
print(data * 10)
print(data + data)
print(data.ndim)
print(data.shape)
print(data.dtype)
data2 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
arr2 = np.array(data2, dtype=np.float64)
print(arr2)
print(arr2.ndim)
print(arr2.shape)
print(arr2.dtype)
print(np.zeros(10))
print(np.zeros((3, 6)))
print(np.empty((2, 3, 2)))
print(np.arange(15))
arr3 = np.array([1, 2, 3, 4, 5])
print(arr3.dtype)
float_arr3 = arr3.astype(np.float64)
print(float_arr3.dtype)
# NumPy數(shù)組的屬性
x3 = np.random.randint(10, size=(3, 4, 5))
print(x3)
print(x3.ndim)
print(x3.shape)
print(x3.size)
print(x3.dtype)
print(x3.itemsize)
print(x3.nbytes)
# 數(shù)組索引:獲取單個(gè)元素
print(x3[1])
print(x3[1, 2])
print(x3[1, 2, 3])
x3[1, 2, 3] = 13
print(x3)
# 數(shù)組切片:獲取子數(shù)組
print(x3[1, :])
print(x3[1])
x3_sub_copy = x3[:2].copy()
print(x3_sub_copy)
# 數(shù)組的變形
# grid = np.arange(0, 9).reshape((3, 3))
grid = np.arange(9).reshape((3, 3))
print(grid)
x = np.array([1, 2, 3])
print(x.reshape(1, 3))
print(x[np.newaxis, :])
print(x.reshape((3, 1)))
print(x.reshape((-1, 1)))
print(x[:, np.newaxis])
# 數(shù)組拼接和分裂
x = np.array([1, 2, 3])
y = np.array([4, 5, 6])
z = [99, 99, 99]
print(np.concatenate([x, y, z]))
grid = np.array([[1, 2, 3],
[4, 5, 6]])
print(np.concatenate([grid, grid]))
print(np.concatenate([grid, grid], axis=1))
# 垂直棧數(shù)組
print(np.vstack([grid, grid]))
# 水平棧數(shù)組
print(np.hstack([grid, grid]))
x = [1, 2, 3, 99, 99, 3, 2, 1]
x1, x2, x3 = np.split(x, [4, 6])
print(x1, x2, x3)
grid = np.arange(16).reshape((4, 4))
upper, lower = np.vsplit(grid, [2])
print(upper)
print(lower)
left, right = np.hsplit(grid, [2])
print(left)
print(right)
輸出
[[0.5488135 0.71518937 0.60276338]
[0.54488318 0.4236548 0.64589411]]
[[5.48813504 7.15189366 6.02763376]
[5.44883183 4.23654799 6.45894113]]
[[1.09762701 1.43037873 1.20552675]
[1.08976637 0.8473096 1.29178823]]
2
(2, 3)
float64
[[ 1. 2. 3. 4.]
[ 5. 6. 7. 8.]
[ 9. 10. 11. 12.]]
2
(3, 4)
float64
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]]
[[[ 1. 2.]
[ 3. 4.]
[ 5. 6.]]
[[ 7. 8.]
[ 9. 10.]
[11. 12.]]]
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]
int64
float64
[[[4 7 6 8 8]
[1 6 7 7 8]
[1 5 9 8 9]
[4 3 0 3 5]]
[[0 2 3 8 1]
[3 3 3 7 0]
[1 9 9 0 4]
[7 3 2 7 2]]
[[0 0 4 5 5]
[6 8 4 1 4]
[9 8 1 1 7]
[9 9 3 6 7]]]
3
(3, 4, 5)
60
int64
8
480
[[0 2 3 8 1]
[3 3 3 7 0]
[1 9 9 0 4]
[7 3 2 7 2]]
[1 9 9 0 4]
0
[[[ 4 7 6 8 8]
[ 1 6 7 7 8]
[ 1 5 9 8 9]
[ 4 3 0 3 5]]
[[ 0 2 3 8 1]
[ 3 3 3 7 0]
[ 1 9 9 13 4]
[ 7 3 2 7 2]]
[[ 0 0 4 5 5]
[ 6 8 4 1 4]
[ 9 8 1 1 7]
[ 9 9 3 6 7]]]
[[ 0 2 3 8 1]
[ 3 3 3 7 0]
[ 1 9 9 13 4]
[ 7 3 2 7 2]]
[[ 0 2 3 8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