python常用函数记录
数组操作
numpy数组尺寸
#数组尺寸
#axis = 0,二维矩阵行数
#axis = 1,二维矩阵列数
np.size(a,1)
#增加行/列
#在arr数据后面填加values,不定义axis,返回一维数组
new = np.append(arr, values)
#增加行axis = 0,增加列axis = 1
new = np.append(arr, values, axis=0)
numpy数组排序
#直接排序
np.sort(x)
#获得排序索引
sort_ind = np.argsort(x)
#使用x的排序索引对其他数据进行排列
y_so = y[sort_ind]
#输出满足要求的元素的坐标索引
y_loc = np.argwhere(y<10)
numpy数组翻转
# 生成数组
a = [[0,1,2,3]]
b = a
print('a,b',a,b)
c=np.append(a,b,axis = 0)
print('c',c)
# 翻转
d=np.flip(c,axis=1)
print('d',d)
输出
a = [[0,1,2,3]]
b = a
print(‘a,b’,a,b)
c=np.append(a,b,axis = 0)
print(‘c’,c)
d=np.flip(c,axis=1)
print(‘d’,d)
numpy向量-数组转换
向量转换为数组
print("g",g)
print(g.shape)
# 转换为matrix
g_matrix= np.mat(g)
# 转换为ndarray
g_arr= g_matrix.A
print("g_arr",g_arr)
print(g_arr.shape)
输出
g [1 2 3 4]
(4,)
g_arr [[1 2 3 4]]
(1, 4)
数组转换为向量
a=np.array([[2,1,2]])
a2=a.reshape(-1)
输出
a2 [2 1 2]
numpy数组取特定位置的值
arr = np.array([[0,1,2],[3,4,5],[6,7,8]])
print(arr)
index1 = np.array([0,1,2]) # 行
index2 = np.array([0,2,1]) # 列
print(arr[index1,index2])
输出
arr [[0 1 2]
[3 4 5]
[6 7 8]]
out [0 5 7]
保存为.npy
np.save("test.npy",a) # 保存文件
b = np.load("test.npy") # 读取文件
读取csv文件
#读取
data_raw = np.loadtxt('test.csv', dtype=np.float32, delimiter=',')
#存储
modified_path = 'test2.csv'
np.savetxt(modified_path , data, fmt='%d', delimiter=',')
注:csv应是纯数字文件
字符串
# 字符串合并
n_str = "crystal"+str(num)
画图
画图
#读取
data_raw = np.loadtxt('test.csv', dtype=np.float32, delimiter=',')
#存储
modified_path = 'test2.csv'
np.savetxt(modified_path , data, fmt='%d', delimiter=',')
图像透明度设置
# alpha=0.3,设置透明度
n_temp, bins_temp, patches_temp = plt.hist(energy_fil_al_cali,bins=400,alpha=0.3,label = n_str)
从colorbar中取颜色做颜色矩阵,用于绘图
color=plt.get_cmap('Paired')(np.linspace(0, 1, 12))
color=plt.cm.Paired(np.linspace(0, 1, 12))
根据矩阵画方格图
A = np.arange(0, 100).reshape(10, 10)
plt.matshow(A)
plt.title("matrix A")
plt.show()