作者:xg123321123 - 时光杂货店
出处:http://blog.csdn.net/xg123321123/article/details/54376598
声明:版权所有,转载请联系作者并注明出处
1 打印数组中所有元素
问题:当数组有大量元素时,想要全部打印出来
解决:
from numpy import *
set_printoptions(threshold='nan')
2 三元表达式
问题:想要用python表达result=5>3?1:0
解决:
1 if 5>3 else 0 ## 为真时的结果 if 判定条件 else 为假时的结果
3 返回数组中符合某一条件的下标
问题:想要用python实现MATLAB中的find函数
解决:
>>a = np.array(a)
>>a
array([1, 2, 3, 1, 2, 3, 1, 2, 3])
>>idx = np.where(a > 2)
>>idx
(array([2, 5, 8], dtype=int32),)
>>a[idx]
array([3, 3, 3])
>>a[a>2]
array([3, 3, 3])
注:np.where()不接受list类型的参数,另外,np.where()也可用于三目运算的情况:
>>y = np.array([1, 2, 3, 4, 5, 6]) # 将奇数转换为偶数,偶数转换为奇数
>>y = np.where(y%2 == 0, y+1, y-1)
>>y
4 遍历判断
问题:遍历的同时,进行判断
解决:
>>a = [1, 2, 3, 1, 2, 3, 1, 2, 3]
>>idx = [idx for (idx, val) in enumerate(a) if val > 2]
>>idx
[2, 5, 8]
>>vals = [val for (idx, val) in enumerate(a) if val > 2]
[3, 3, 3]
5 处理NaN
问题:将nan所在的列非nan的均值赋给这些nan值
解决:
>>A = np.array([[1, 2, 3, 4], [5, 6, np.nan, 8], [9, 10, 11, np.nan]])
>>idx = np.where(np.isnan(A))
>>idx
(array([1, 2], dtype=int32), array([2, 3], dtype=int32))
for i in idx:
A[i[0], i[1]] = A[~np.isnan(A[:, i[1]]), i[1]].mean()
6 随机数
问题:给出几个常用的随机数函数
解决:
>> random.random() #生成一个0到1的随机符点数: 0 <= n < 1.0
>> random.uniform(a, b) #生成一个指定范围内的随机浮点数
>> random.randint(a, b) #生成一个指定范围内的整数
>> random.choice(sequence) #从序列中获取一个随机元素;list, tuple, 字符串都属于sequence
>> random.randrange([start], stop[, step]) #从指定范围内,按指定基数递增的集合中获取一个随机数; random.randrange(10, 100, 2)在结果上与 random.choice(range(10, 100, 2)等效
>> random.shuffle(x[, random]) #将一个列表中的元素打乱
>> random.sample(sequence, k) #从指定序列中随机获取指定长度的片断,sample函数不会修改原有序列
7 读写文件
问题:几种读写文件的方法
解决:
np.savetxt("result.txt", numpy_data, fmt='%.4f') #将numpy数据保存为留有4位小数的浮点数,fmt='%.18e'则是保留8位小数的科学计数法
numpy_data = np.loadtxt("result.txt",delimiter=",") #以delimiter为分隔符读入数据
file=open('data.txt','w') #保存list数据
file.write(str(list_data));
file.close()
>> f = file("result.npy", "wb")
>> np.save(f, a) # 顺序将a,b,c保存进文件对象f
>> np.save(f, b)
>> np.save(f, c)
>> f.close()
>> f = file("result.npy", "rb")
>> np.load(f) # 顺序从文件对象f中读取内容
array([0, 1, 2, 3, 4, 5, 6, 7])
>> np.load(f)
array([ 0, 1, 3, 6, 10, 15, 21, 28])
>> np.load(f)
array([ 0, 2, 5, 9, 14, 20, 27, 35])
>> [line.strip('\n').strip('\r') for line in open('result.txt')] #返回一个由result.txt构成的list
8 strip()和split()
strip()
s为字符串,rm为要删除的字符序列,只能删除开头或是结尾的字符或字符串;不能删除中间的字符或字符串
s.strip(rm) 删除s字符串中开头、结尾处,位于 rm删除序列的字符
s.lstrip(rm) 删除s字符串中开头处,位于 rm删除序列的字符
s.rstrip(rm) 删除s字符串中结尾处,位于 rm删除序列的字符
- 当rm为空时,默认删除空白符(包括’\n’, ‘\r’, ‘\t’, ’ ‘)
- 这里的rm删除序列是只要边(开头或结尾)上的字符在删除序列内,就删除掉
split()
- split返回的是一个列表
不带参数,默认是空白字符。如下:
按某一个字符/字符串分割
按某一个字符/字符串分割n次
按某一字符/字符串分割n次,并将分割后的字符串/字符赋给新的n+1个变量
9 将数组转化为图片
问题:如题
解决:
>> img = Image.fromarray(image_array) #将image_array数组转换为img
>> img.save('outfile.jpg')
>> #上述方法不行的话,还可以尝试下面的方法
>> import scipy.misc
>> scipy.misc.toimage(image_array, cmin=0.0, cmax=255.0).save('outfile.jpg') #将img_array数组存储为outfile.jpg
10 绘制图像
问题:如题
解决:
>> #imshow()函数格式为:
>> #matplotlib.pyplot.imshow(X, cmap=None)
>> #X: 要绘制的图像或数组。
>> #cmap: 颜色图谱(colormap), 默认绘制为RGB(A)颜色空间。
>> #还有其它可选的颜色图谱如:gray,hot,cool等等
>>
>> import matplotlib.pyplot as plt
>> plt.figure(num='astronaut',figsize=(8,8)) #创建一个名为astronaut的窗口,并设置大小
>> plt.subplot(2,2,1) #将窗口分为两行两列四个子图,则可显示四幅图片
>> plt.title('origin image') #第一幅图片标题
>> plt.imshow(img) #绘制第一幅图片
>> plt.subplot(2,2,2) #第二个子图
>> plt.title('R channel') #第二幅图片标题
>> plt.imshow(img[:,:,0],plt.cm.gray) #绘制第二幅图片,且为灰度图
>> plt.axis('off') #不显示坐标尺寸
>> plt.subplot(2,2,3) #第三个子图
>> plt.title('G channel') #第三幅图片标题
>> plt.imshow(img[:,:,1],plt.cm.gray) #绘制第三幅图片,且为灰度图
>> plt.axis('off') #不显示坐标尺寸
>> plt.subplot(2,2,4) #第四个子图
>> plt.title('B channel') #第四幅图片标题
>> plt.imshow(img[:,:,2],plt.cm.gray) #绘制第四幅图片,且为灰度图
>> plt.axis('off') #不显示坐标尺寸
>> plt.show() #显示窗口
>> # 更多详细用法,见下面引用链接
11 格式化输出dict
问题:如题
解决:
>>#格式化输出dict
>>import pprint
>>dic = {}
>>for i in xrange(201):
>> dic[i] = "value for %d" % i
>># 自定义缩进为4空格
>>pp = pprint.PrettyPrinter(indent=4)
>>pp.pprint(dic)
12 any
any(x): 判断x是否为空对象,如果都为空、0、false,或者x直接就是空对象,则返回false,如果不都为空、0、false,则返回true
all(x): 如果x的所有元素都不为0、”、False, 或者x直接就是空对象,则返回True,否则返回False
13 保存 json 文件
- 一般情况:
with open("annotation_train_vg.json","w") as f:
json.dump(your_data,f)
print("well done...")
- 有时候会报错(如下),得自己构造类:
#raise TypeError(repr(o) + " is not JSON serializable")
#TypeError: xx is not JSON serializable
class MyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
return obj.tolist()
else:
return super(MyEncoder, self).default(obj)
jsObj = json.dumps(your_data, cls=MyEncoder)
fileObject = open('annotation_test_vg.json', 'w')
fileObject.write(jsObj)
fileObject.close()
本篇博客主要整理自
python 中的三元表达式(三目运算符)
Python vs Matlab—— find 与 np.where
Python中的random模块
numpy矩阵运算和文件存储
python strip()函数和Split函数的用法总结
python数字图像处理(5):图像的绘制