CHH3213 / Note-Ubuntu_CHH3213

ubuntu系统CHH3213上做的笔记
0 stars 0 forks source link

40. python 的np.insert和delete,np.empty用法 #40

Open CHH3213 opened 3 years ago

CHH3213 commented 3 years ago

使用numpy.insert()函数将元素、行或列插入(添加)到NumPy数组ndarray中。

例如:

import numpy as np

a = np.arange(5)
print(a)
# [0 1 2 3 4]

print(np.insert(a, 2, 10))
# [ 0  1 10  2  3  4]

print(np.insert(a, 1,[10, 20, 30]))
# [ 0 10 20 30  1  2  3  4]

print(np.insert(a, [0, 2, 4], [10, 20, 30]))
# [100   0   1 101   2   3 102   4]

numpy array数组删除一列或一行 np.delete

删除一列

dataset=[[1,2,3],[2,3,4],[4,5,6]]
import numpy as np
dataset = np.delete(dataset, -1, axis=1)
dataset
array([[1, 2],
       [2, 3],
       [4, 5]])

删除多列

arr = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
np.delete(arr, [1,2], axis=1)
array([[ 1,  4],
       [ 5,  8],
       [ 9, 12]])

np.empty声明空的数组