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.

 
 
 

来自为知笔记(Wiz)

Useful NumPy functions: Reshape, Argpartition, Clip, Extract, Setdiff1d的更多相关文章

  1. numpy中的argpartition

    numpy.argpartition(a, kth, axis=-1, kind='introselect', order=None) 在快排算法中,有一个典型的操作:partition.这个操作指: ...

  2. numpy 矩阵变换 reshape ravel flatten

    1. 两者的区别在于返回拷贝(copy)还是返回视图(view),numpy.flatten()返回一份拷贝,对拷贝所做的修改不会影响(reflects)原始矩阵,而numpy.ravel()返回的是 ...

  3. python库numpy的reshape的终极解释

    a = np.arange(2*4*4) b = a.reshape(1,4,4,2)           #应该这样按反序来理解:最后一个2是一个只有2个元素的向量,最后的4,2代表4×2的矩阵,最 ...

  4. 小白眼中的AI之~Numpy基础

      周末码一文,明天见矩阵- 其实Numpy之类的单讲特别没意思,但不稍微说下后面说实际应用又不行,所以大家就练练手吧 代码裤子: https://github.com/lotapp/BaseCode ...

  5. numpy基本用法

    numpy 简介 numpy的存在使得python拥有强大的矩阵计算能力,不亚于matlab. 官方文档(https://docs.scipy.org/doc/numpy-dev/user/quick ...

  6. numpy快速指南

    Quickstart tutorial 引用https://docs.scipy.org/doc/numpy-dev/user/quickstart.html Prerequisites Before ...

  7. 课程一(Neural Networks and Deep Learning),第二周(Basics of Neural Network programming)—— 3、Python Basics with numpy (optional)

    Python Basics with numpy (optional)Welcome to your first (Optional) programming exercise of the deep ...

  8. Python Basics with Numpy

    Welcome to your first assignment. This exercise gives you a brief introduction to Python. Even if yo ...

  9. Python Basics with numpy (optional)

    Python Basics with Numpy (optional assignment) Welcome to your first assignment. This exercise gives ...

随机推荐

  1. spring框架学习(一)——IOC/DI

    什么是Spring框架: Spring是一个基于IOC和AOP的结构J2EE系统的框架: IOC 反转控制 是Spring的基础,Inversion Of Control,简单说就是创建对象由以前的程 ...

  2. 简要介绍Linux网络服务的种类

    如果有人问你Linux最强大的功能是什么,你大概会回答“是网络功能”.Lmux操作系统的优势之一就是网络功能了,这包含比较稳定的系统资源分配,以及较为安全的网络防护能力,所以许多人都喜欢用它来进行网络 ...

  3. FullCalendar日历插件说明文档(看到这篇手册,解决了困扰我3天的js问题)

    FullCalendar提供了丰富的属性设置和方法调用,开发者可以根据FullCalendar提供的API快速完成一个日历日程的开发,本文将FullCalendar的常用属性和方法.回调函数等整理成中 ...

  4. Java 字符串(二)字符串常用操作

    一.连接字符串 1.连接多个字符串 使用“+”运算符可以实现连接多个字符串的功能.“+” 运算符可以连接多个运算符并产生一个 String 对象. 2.连接其他数据类型 字符串与其他基本数据类型进行连 ...

  5. Jnetpcap简述

    Jnetpcap简述 最近需要做一个本地网络流量分析的项目,基于 Java 语言,上网查了很多资料,最后利用 Jnetpcap 实现了,这里做个记录. 这里先列一下我用到的工具以及版本: Eclips ...

  6. python 使用Anaconda管理项目环境

    Pycharm没有内置的python解释器,需要我们自己下载python解释器. 在很多python项目中,会导入第三方的模块,逐个去下载导入很不方便. 我们通常使用Anaconda来管理python ...

  7. 在 Vim 中,删除 ^@ 符号的几种方法

    在 Vim 中,^@ 表示 ASCII 码中的 NULL 字符,编码为 0x00,占用一个字节. 删除方法 方法1,采用 <CTRL-V><CTRL-J> 或 <CTRL ...

  8. Echarts实现Excel趋势线和R平方计算思路

    测试数据 [19550, 7.1 ],[22498, 8.44 ],[25675, 9.56 ],[27701, 10.77],[29747, 11.5 ],[32800, 12.27],[34822 ...

  9. 响应式js库——rxjs

    原文地址:https://rxjs.dev/guide/overview 简介 RxJS 是组合异步以及基于事件的使用可观察者序列的程序类库.它提供一个核心类型,Observable,附属类型(Obs ...

  10. SPRINGBOOT注解最全详解(

    #     SPRINGBOOT注解最全详解(整合超详细版本)          使用注解的优势:               1.采用纯java代码,不在需要配置繁杂的xml文件           ...