Useful NumPy functions: Reshape, Argpartition, Clip, Extract, Setdiff1d
In everyday data processing for Machine Learning and Data Science projects, we encounter unique situations, those require boilerplate code to solve the problem. Over the period some of those are converted into base features provided by the core language or the package itself as per need and usage from the community. Here I am sharing 5 elegant python Numpy functions, which can be used for efficient and neat data manipulation.
1) Use of -1 in Reshape
Numpy allows us to reshape a matrix provided new shape should be compatible with the original shape. One interesting aspect of this new shape is, we can give one of the shape parameter as -1. It simply means that it is an unknown dimension and we want Numpy to figure it out. Numpy will figure this by looking at the ‘length of the array and remaining dimensions’ and making sure it satisfies the above mentioned criteria. Let's see one example now.
Pictorial representation of different reshape with one dimension as -1
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) a.shape (2, 4)
Suppose we give row as 1 and -1 as column then Numpy will able to find column as 8.
a.reshape(1,-1)
array([[1, 2, 3, 4, 5, 6, 7, 8]])
Suppose we give row as -1 and 1 as column then Numpy will able to find row as 8.
a.reshape(-1,1) array([[1], [2], [3], [4], [5], [6], [7], [8]])
Similarly below are possible.
a.reshape(-1,4) array([[1, 2, 3, 4], [5, 6, 7, 8]])a.reshape(-1,2) array([[1, 2], [3, 4], [5, 6], [7, 8]])a.reshape(2,-1) array([[1, 2, 3, 4], [5, 6, 7, 8]])a.reshape(4,-1) array([[1, 2], [3, 4], [5, 6], [7, 8]])
This is also applicable to any higher level tensor reshape as well but only one dimension can be given -1.
a.reshape(2,2,-1) array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])a.reshape(2,-1,1) array([[[1], [2], [3], [4]], [[5], [6], [7], [8]]])
If we try to reshape a non-compatible shape or more than one unknown shape then there will be an error message.
a.reshape(-1,-1) ValueError: can only specify one unknown dimensiona.reshape(3,-1) ValueError: cannot reshape array of size 8 into shape (3,newaxis)
To summarize, when reshaping an array, the new shape must contain the same number of elements as the old shape, meaning the products of the two shapes’ dimensions must be equal. When using a -1, the dimension corresponding to the -1 will be the product of the dimensions of the original array divided by the product of the dimensions given to reshape
so as to maintain the same number of elements.
2) Argpartition : Find N maximum values in an array
Numpy has a function called argpartition which can efficiently find largest of N values index and in-turn N values. It gives index and then you can sort if you need sorted values.
array = np.array([10, 7, 4, 3, 2, 2, 5, 9, 0, 4, 6, 0])index = np.argpartition(array, -5)[-5:] index array([ 6, 1, 10, 7, 0], dtype=int64)np.sort(array[index]) array([ 5, 6, 7, 9, 10])
3) Clip : How to keep values in an array within an interval
In many data problem or algorithm (like PPO in Reinforcement Learning) we need to keep all values within an upper and lower limit. Numpy has a built in function called Clip that can be used for such purpose. Numpy clip() function is used to Clip (limit) the values in an array. Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of [-1, 1] is specified, values smaller than -1 become -1, and values larger than 1 become 1.
Clip example with min value 2 and maximum value 6
#Example-1 array = np.array([10, 7, 4, 3, 2, 2, 5, 9, 0, 4, 6, 0]) print (np.clip(array,2,6))[6 6 4 3 2 2 5 6 2 4 6 2]#Example-2 array = np.array([10, -1, 4, -3, 2, 2, 5, 9, 0, 4, 6, 0]) print (np.clip(array,2,5))[5 2 4 2 2 2 5 5 2 4 5 2]
4) Extract: To extract specific elements from an array based on condition
We can use Numpy extract() function to extract specific elements from an array that matches the condition.
arr = np.arange(10) arrarray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])# Define the codition, here we take MOD 3 if zero condition = np.mod(arr, 3)==0 conditionarray([ True, False, False, True, False, False, True, False, False,True])np.extract(condition, arr) array([0, 3, 6, 9])
Similarly, we can use direct condition with combination of AND and OR if required like
np.extract(((arr > 2) & (arr < 8)), arr)array([3, 4, 5, 6, 7])
5) setdiff1d : How to find unique values in an array compared to another
Return the unique values in an array that are not in present in another array. This is equivalent to set difference of two arrays.
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) b = np.array([3,4,7,6,7,8,11,12,14]) c = np.setdiff1d(a,b) carray([1, 2, 5, 9])
Final Note :
These are 5 Numpy functions which are not used frequently by the community but they are neat and elegant. In my view, we should use them whenever there is similar situation as these provide not just less code but mostly smart way of achieving a solution for a complex problem.
原文地址:https://www.cnblogs.com/jins-note/p/11730948.html
- linux下编辑VI窗口插入与编辑命令
- rman中三个不完全恢复场景(r6笔记第16天)
- 关于delete,drop,truncate的问题 (r6笔记第14天)
- R语言进行分析,比较详细的一篇,亲测过哦
- DeepMind 开源基于 MuJoCo 物理引擎强化学习工具 Control Suite
- hadoop常用的基本命令,HIVE复制文件,修改文件名
- gc服务器慢的原因分析 (r6笔记第14天)
- AI 玩微信跳一跳的正确姿势——跳一跳 Auto-Jump 算法详解
- 干货 | 深入理解Python装饰器
- 11g dataguard使用总结(r5笔记第12天)
- centos7.4下配置django+uwsgi+nginx
- 11g rac配置scan ip(r6笔记第30天)
- 【C++概念】---vector用法
- 浅谈Orabbix监控指标(r6笔记第27天)
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法
- Hadoop入门---(wordcount)统计单词出现的次数
- JS去除字符串的空格
- insertionSoft(插入排序) 2.1-1 And 重写insertionSoft 2.1-2
- Swagger-Springboot-mybatis-mysql
- Python+java+websocket+SpringMVC实时监控数据库中的表
- 基于Java图形界面的IPV4与网址的地址解析器
- 如何在千里之外能访问自己的电脑?(FRP)
- 三分钟Docker-镜像、容器实战篇
- 看懂今天这个!你就是个真正的javaer!
- 猿进化系列7——一文搞懂IO
- 猿进化系列13——一文搞懂MVC相关框架套路
- 猿进化系列16——实战之一学会SQL开发正确姿势
- 猿进化系列17——实战之一文学会前后端分离套路
- 基于Java的模拟写字板的设计与实现
- 猿思考系列2——一文搞懂同步并发套路