1. 访问和删除和插入 ndarray 中的元素
1.1 访问ndarry元素
1.1.1 索引访问元素
import numpy as np
x = np.array([1, 2, 3, 4, 5])
print(x[0])
print(x[-1])
1
5
1.1.2 元素赋值
x[3] = 5
x[4] = 4
print(x)
[1 2 3 5 4]
1.1.3 二维数组
x = np.arange(1,10).reshape(3,3)
print(x)
print(x[1,1])
x[1,1] = 0
print(x[1,1])
[[1 2 3]
[4 5 6]
[7 8 9]]
5
0
1.2 删除ndarray元素
x = [1, 2, 3, 4, 5, 0]
y = np.arange(1,17).reshape(4,4)
print(x)
print(y)
a = np.delete(x,[0,4])
print(a)
b = np.delete(y, 0, axis = 0)
print(b)
b = np.delete(y, 3, axis = 1)
print(b)
[1, 2, 3, 4, 5, 0]
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]
[13 14 15 16]]
[2 3 4 0]
[[ 5 6 7 8]
[ 9 10 11 12]
[13 14 15 16]]
[[ 1 2 3]
[ 5 6 7]
[ 9 10 11]
[13 14 15]]
1.3 添加ndarray元素
1.3.1 append 方法
x = np.array([1, 2, 3, 4, 5])
y = np.arange(1,10).reshape(3,3)
print("Origin x is : \n{}\n".format(x))
print("Origin y is : \n{}\n".format(y))
a = np.append(x, [6, 7, 8])
print("After append x is:\n{}\n".format(a))
b = np.append(y,[ [10, 11, 12]], axis = 0)
print("After append y is:\n{}\n".format(b))
z = np.append(y, [[10],[11],[12]], axis = 1)
print("After append y is:\n{}\n".format(z))
#注 参数中的value向量的维数必须与目标向量的维数完全一致,否则会报错
Origin x is :
[1 2 3 4 5]
Origin y is :
[[1 2 3]
[4 5 6]
[7 8 9]]
After append x is:
[1 2 3 4 5 6 7 8]
After append y is:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
After append y is:
[[ 1 2 3 10]
[ 4 5 6 11]
[ 7 8 9 12]]
1.3.2 insert 方法
x = np.array([1, 2, 3, 4, 5])
y = np.arange(1,10).reshape(3,3)
print("Origin x is : \n{}\n".format(x))
print("Origin y is : \n{}\n".format(y))
a = np.insert(x, 3, [0, 1, 2])
print("After insert x is:\n{}\n".format(a))
b = np.insert(y, 1, [5, 6, 7], axis = 0)
print("After insert y is:\n{}\n".format(b))
b = np.insert(y, 1, [5,6,7], axis = 1)
print("After insert y is:\n{}\n".format(b))
Origin x is :
[1 2 3 4 5]
Origin y is :
[[1 2 3]
[4 5 6]
[7 8 9]]
After insert x is:
[1 2 3 0 1 2 4 5]
After insert y is:
[[1 2 3]
[5 6 7]
[4 5 6]
[7 8 9]]
After insert y is:
[[1 5 2 3]
[4 6 5 6]
[7 7 8 9]]
1.3.3 vstack 和 hstack方法
x = np.array([1,2])
Y = np.array([[3,4],[5,6]])
print()
print('x = ', x)
print()
print('Y = \n', Y)
z = np.vstack((x,Y))
w = np.hstack((Y,x.reshape(2,1)))
print()
print('z = \n', z)
print()
print('w = \n', w)
x = [1 2]
Y =
[[3 4]
[5 6]]
z =
[[1 2]
[3 4]
[5 6]]
w =
[[3 4 1]
[5 6 2]]