Python vs Matlab—— find 与 np.where
来源:互联网 发布:js实现的简单的小特效 编辑:程序博客网 时间:2024/06/05 16:20
matlab中的find函数
matlab中find的函数的强大之处在于其能返回下标,且视返回参数的个数,返回以列全排序的一维下标(返回参数的个数为1),返回行列索引的二维坐标(返回参数的个数为2):
>>A = [1, 2, 3; 1, 2, 3; 1, 2, 3]>>idx = find(A > 2)idx = 7 8 9>>A(idx)ans 3 3 3% 当然也可以更简洁地索引符合某一条件(predicate,断言)的元素>>A(A>2)ans 3 3 3>>[rows, cols] = find(A > 2)rows = 1 2 3cols = 3 3 3
python的一般处理
>>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, vals) in enumerate(a) if val > 2][3, 3, 3]
python中与matlab的find函数等价的内置函数
python
或者numpy
中能够返回符合某一条件的下标的函数是np.where()
,不过np.where()
并不接受list
类型的参数,可见np.where()
既可以接收三个参数,用于三目运算,也可接收一个参数,返回符合条件的下标。
>>a = np.array(a)>>aarray([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() 用于返回断言成立时的索引,返回值的形式为 arrays of tuple,由 np.array 构成的 tuple,一般 tuple 的 len 为2(当判断的对象是多维数组时),哪怕是一维数组返回的仍是 tuple,此时tuple 的 len 为 1;
- np.where()[0] 表示行的索引,
- np.where()[1] 则表示列的索引
np.where()
用于三目运算的情况:
>>y = np.array([1, 2, 3, 4, 5, 6]) # 将奇数转换为偶数,偶数转换为奇数>>y = np.where(y%2 == 0, y+1, y-1)>>y array([0, 3, 2, 5, 4, 7])
处理NaN(not a number)
将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()
1 1
- Python vs Matlab—— find 与 np.where
- find 和 np.where
- Matlab与Python中find/where、reshape、eig的区别
- Python Tricks(一)—— np.where 与最大最小截断
- [python]关于np.where与np.in1d合用
- python np.where()
- python np.where
- Python基础——min/max与np.argmin/np.argmax
- Python 基础——range() 与 np.arange()
- Python 基础——range() 与 np.arange()
- np.where
- Python数据分析(八)-xrange,range,arange与np.where
- python 采样——np.linspace
- matlab vs python
- numpy 之 np.where
- np.where函数
- numpy: np.where
- 科学计算:Python VS. MATLAB (2)----准备与前提
- 海尔T520智能扫地机器人使用评测
- activiti与spring集成(maven)
- linux权限篇【一】
- MFC中获取各个窗体之间的句柄或者指针对象的方法 .
- WebLogic Tuxedo Connector 快速入门指南
- Python vs Matlab—— find 与 np.where
- 定制Android系统开发之六——系统服务JNI的实现分析
- iOS开发 在真机中将NSLog日志存入文件并保存到document目录
- SpringMVC filter设置例外的请求
- OSGI ——平台启动
- 矩阵及其运算
- linux权限篇【二】
- iOS 获取当前点击的cell相对于self.view的位置
- svm中的数学和算法