numpy的一些基础操作总结(1)
- numpy基础用法
-
- 1 使用其他函数创建数组
- 2 花式索引 利用嵌套列表进行索引
- 3 数组形状的改变
- 4 排序
- 5 搜索
- 6 字符串操作
- 7 组合
numpy基础用法
1 使用其他函数创建数组
import numpy as np
np.arange(0, 10, 1)
np.linspace(1, 10, 10)
np.linspace(1, 10, 10, endpoint=False)
np.linspace(1, 10, 11)
np.zeros([4, 5])
np.eye(6)
np.diag([3, 4])
np.ones([2, 3])
2 花式索引 利用嵌套列表进行索引
import numpy as np
data2 = ((8.5, 6, 4.1, 2, 0.7), (1.5, 3, 5.4, 7.3, 9), (3.2, 4.5, 6, 3, 9), (11.2, 13.4, 15.6, 17.8, 19))
arr2 = np.array(data2)
arr2[[1, 0, 3, 2]]
arr2[[3, 2]]
arr2[[3, 2], [0, 1]]
arr2[:, [3, 1]]
arr2[:, 1]
arr2[:, [1]]
3 数组形状的改变
import numpy as np
data = ((8.5, 6, 4.1, 2, 0.7), (1.5, 3, 5.4, 7.3, 9), (3.2, 4.5, 6, 3, 9), (11.2, 13.4, 15.6, 17.8, 19))
arr = np.array(data)
arr1 = arr.reshape(10, 2)
arr2=arr.resize((10,2))
arr.shape=(10,2)
arr.ravel()
arr.ravel(order='F')
arr.flatten()
arr.flatten(order='F')
arr.reshape(-1)
arr.reshape(2, -1)
arr.reshape(-1, 1)
arr.reshape(-1, )
a=arr.reshape(-1, ).ndim
arr_t = arr.ravel()
arr_t[np.newaxis,:]
arr_t[np.newaxis,:].shape
4 排序
import numpy as np
s = np.array([1, 2, 3, 4, 3, 1, 2, 2, 4, 6, 7, 2, 4, 8, 4, 5])
np.sort(s)
np.argsort(s)
sorted(s, reverse=True)
arr1 = np.array([[0, 1, 3], [4, 2, 9], [4, 5, 9], [1, -3, 4]])
np.sort(arr1)
np.sort(arr1, axis=0)
np.sort(arr1, axis=1)
5 搜索
np.where(amount[:, 1] > 10000, 1, 0)
np.where(amount[:, 1] > 10000, amount[:, 1], 0)
doubt = np.extract(data[:, -2] == '可疑', data[:, -4])
6 字符串操作
str_list = ['hello', 'world']
str_list = [i.upper() for i in str_list]
str_arr = np.char.upper(str_list)
np.char.add(['中国', '国庆'], ['海军', '大阅兵'])
np.char.multiply(['中国', '万岁'], 3)
np.char.join([':', ';'], ['hello', 'world'])
data = np.array(data)
np.char.strip(data[:, 1], ' ')
data[:, 6]
np.char.replace(data[:, 6], ',', '')
np.char.find(data[:, -3], '保证')
data[:, 1] = np.char.strip(data[:, 1], ' ')
np.char.isdigit(data[:, 1])
np.char.isalpha(data[:, 1])
np.char.count(data[:, 1], '1')
np.char.startswith(data[:, 2], '沂水农商行')
np.char.endswith(data[:, 1], 'X')
7 组合
import numpy as np
arr1 = np.arange(12).reshape(3, 4)
arr2 = np.array([[8.5, 6, 4.1, 2, 0.7], [1.5, 3, 5.4, 7.3, 9], [3.2, 4.5, 6, 3, 9]])
np.hstack((arr1, arr2))
arr3 = np.array([[8.5, 6, 4.1, 0.9], [1.5, 3, 5.4, 1.1], [3.2, 4.5, 6, 7.3], [11.2, 13.4, 15.6, 14.2]])
np.vstack((arr1, arr3))
np.concatenate((arr1, arr2), axis=1)
np.concatenate((arr1, arr3), axis=0)