Python cheatsheet
pandas
df = pd.read_csv('path') # read .csv
df.to_csv('path') # write .csv df.to_csv('path',header=True,index=True),header是列名,index是数字行名,两者默认都是True,将header设为False,第一行会称为列名,将index设为True,会额外加上行数列作为列名
matplotlib
scatter(x,y,linewidth) # linewidth 点大小
plt.imshow(img,cmap='gray') # 展示灰度图像
plt.axis('off') # 关闭坐标轴
设置子图大小
plt.subplots(figsize=(15,15))
plt.subplot(121)
...
画网格状的子图
fig, axs = plt.subplots(16, 11, figsize=(11*1.5, 16*1.5))
for i in range(16):
axs[i, 0].set_ylabel('dim {}'.format(i), size='large')
for j in range(11):
axs[i, j].imshow(perturbed_reconstructions[i][j], cmap='gray')
axs[i, j].set_yticks([])
axs[i, j].set_xticks([])
交互模式
plt.ion()
与阻塞模式相对
plt.ioff()
绘图是否会暂停程序
mask
plt.gca().imshow(img, alpha=0.2)
m = plt.gca().matshow((log_density_prediction[0, :, :, 0]), alpha=0.5, cmap=plt.cm.RdBu)
输出格式
print("{:.2f}".format(1/2)) # 保留两位小数
计时
import time
start = time.time()
...
end = time.time()
print(end-start)
numpy
- 重复列的矩阵
- 加减乘,既可以用在维数相同的向量上,也可以用在列数相同的向量上
第二个例子表明,即便行数相等,numpy也不会执行将向量加到每一列上的加(减、乘)法>>> import numpy as np >>> a = np.zeros((3,3)) >>> b = np.array([1,2,3]) >>> a + b array([[1., 2., 3.], [1., 2., 3.], [1., 2., 3.]]) >>> c = np.zeros((3,2)) >>> b + c Traceback (most recent call last): File "<stdin>", line 1, in <module>ValueError: operands could not be broadcast together with shapes (3,) (3,2)
- argmax,argmax的axis参数指定求argmax的维度,如果axis=0则说明结果是一行(0代表行),就是在列上求最大值,如果axis=1则说明结果是一列(1代表列),就是在行上求最大值
- 索引
多维索引的写法>>> a = np.array([[0,0],[1,1],[2,2]]) >>> b = np.zeros((5,5)) >>> b[a] = 1 array([[1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.], [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.]]) >>> c = np.zeros((5,5)) >>> c[a[:,0],a[:,1]] = 1 array([[1., 0., 0., 0., 0.], [0., 1., 0., 0., 0.], [0., 0., 1., 0., 0.], [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.]])
- 等间距数组
np.linspace(st,ed,num)
- 排序1
按照某列排序
a = np.array([[1,2,3],[4,5,6],[0,0,1]])
a_arg = np.argsort(a[:,1]) #按第’1’列排序
a_arg = np.argsort(a[:,-2]) #按第倒数第2列排序
a = a[a_arg].tolist() - 矩阵转化成列表
ndarray.tolist(),按行转化为列表 - OpenCV Error: Assertion failed (points.checkVector(2, CV_32S) >= 0) in fillConvexPoly, file …/OpenCV-2.4.0/modules/core/src/drawing.cpp, line 2017
将points改成np.int32类型,通过.astype(np.int32)
np.full()全是某数的矩阵
- unsqueeze
I = I[:,:,np.newaxis]
f-string
- 格式
>>>a = 1.1111111
>>>print(f"{a:.2f}")
1.11
列出目录下文件
>>>import os
>>>os.listdir(.)
只能列一级的
错误
不要将模块命名为一些自带的模块名
比如random.py
否则会让所有依赖random模块的包出现问题
排序字典
为了排序字典可以通过元组的方法进行
# a 是一个字典
sorted_a = sorted([(value,key) for key,value in a]) # 按照value来排序
sorted_a = sorted([(key,value) for key,value in a]) # 按照key来排序
argmax
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
index = np.unravel_index(a.argmax(), a.shape)
print(index)
>>>(1, 2)
分割列表
https://www.geeksforgeeks.org/python-split-nested-list-into-two-lists/
# Python code to demonstrate
# splitting nested list
# into 2 lists
# initialising nested lists
ini_list = [[1, 2], [4, 3], [45, 65], [223, 2]]
# printing initial lists
print ("initial list", str(ini_list))
# code to split it into 2 lists
res1, res2 = map(list, zip(*ini_list))
# printing result
print("final lists", res1, "\n", res2)
https://www.jianshu.com/p/e667d5b3c328 ↩︎