Python 数据处理更容易的12个辅助函数总结(数据函数)

您所在的位置:网站首页 numpy和pandas数据处理函数 Python 数据处理更容易的12个辅助函数总结(数据函数)

Python 数据处理更容易的12个辅助函数总结(数据函数)

2022-10-03 23:44| 来源: 网络整理| 查看: 265

目录Numpy 的 6 种高效函数argpartition()allclose()clip()extract()where()percentile()Pandas 数据统计包的 6 种高效函数read_csv(nrows=n)map()apply()isin()copy()select_dtypes()技术交流

大家好,今天给大家分享 12 个 Python 函数,其中 Numpy 和 Pandas 各6个,这些实用的函数会令数据处理更为容易、便捷。

同时,你也可以在 GitHub 项目中找到本文所用代码的 Jupyter Notebook,欢迎收藏学习,喜欢点赞支持。

项目地址:https://github.com/kunaldhariwal/12-Amazing-Pandas-NumPy-Functions

Numpy 的 6 种高效函数

首先从 Numpy 开始。Numpy 是用于科学计算的 Python 语言扩展包,通常包含强大的 N 维数组对象、复杂函数、用于整合 C/C++和 Fortran 代码的工具以及有用的线性代数、傅里叶变换和随机数生成能力。

除了上面这些明显的用途,Numpy 还可以用作通用数据的高效多维容器(container),定义任何数据类型。这使得 Numpy 能够实现自身与各种数据库的无缝、快速集成。

接下来一一解析 6 种 Numpy 函数。

argpartition()

借助于 argpartition(),Numpy 可以找出 N 个最大数值的索引,也会将找到的这些索引输出。然后我们根据需要对数值进行排序。

x = np.array([12, 10, 12, 0, 6, 8, 9, 1, 16, 4, 6, 0])index_val = np.argpartition(x, -4)[-4:] index_val array([1, 8, 2, 0], dtype=int64)np.sort(x[index_val]) array([10, 12, 12, 16])

allclose()

allclose() 用于匹配两个数组,并得到布尔值表示的输出。如果在一个公差范围内(within a tolerance)两个数组不等同,则 allclose() 返回 False。该函数对于检查两个数组是否相似非常有用。

array1 = np.array([0.12,0.17,0.24,0.29]) array2 = np.array([0.13,0.19,0.26,0.31])# with a tolerance of 0.1, it should return False: np.allclose(array1,array2,0.1) False# with a tolerance of 0.2, it should return True: np.allclose(array1,array2,0.2) True

clip()

Clip() 使得一个数组中的数值保持在一个区间内。有时,我们需要保证数值在上下限范围内。为此,我们可以借助 Numpy 的 clip() 函数实现该目的。给定一个区间,则区间外的数值被剪切至区间上下限(interval edge)。

x = np.array([3, 17, 14, 23, 2, 2, 6, 8, 1, 2, 16, 0])np.clip(x,2,5) array([3, 5, 5, 5, 2, 2, 5, 5, 2, 2, 5, 2])

extract()

顾名思义,extract() 是在特定条件下从一个数组中提取特定元素。借助于 extract(),我们还可以使用 and 和 or 等条件。

# Random integers array = np.random.randint(20, size=12) array array([ 0, 1, 8, 19, 16, 18, 10, 11, 2, 13, 14, 3])# Divide by 2 and check if remainder is 1 cond = np.mod(array, 2)==1 cond array([False, True, False, True, False, False, False, True, False, True, False, True])# Use extract to get the values np.extract(cond, array) array([ 1, 19, 11, 13, 3])# Apply condition on extract directly np.extract(((array < 3) | (array > 15)), array) array([ 0, 1, 19, 16, 18, 2])

where()

Where() 用于从一个数组中返回满足特定条件的元素。比如,它会返回满足特定条件的数值的索引位置。Where() 与 SQL 中使用的 where condition 类似,如以下示例所示:

y = np.array([1,5,6,8,1,7,3,6,9])# Where y is greater than 5, returns index position np.where(y>5) array([2, 3, 5, 7, 8], dtype=int64),)# First will replace the values that match the condition, # second will replace the values that does not np.where(y>5, "Hit", "Miss") array([ Miss , Miss , Hit , Hit , Miss , Hit , Miss , Hit , Hit ],dtype=

版权声明:本站文章来源标注为YINGSOO的内容版权均为本站所有,欢迎引用、转载,请保持原文完整并注明来源及原文链接。禁止复制或仿造本网站,禁止在非www.yingsoo.com所属的服务器上建立镜像,否则将依法追究法律责任。本站部分内容来源于网友推荐、互联网收集整理而来,仅供学习参考,不代表本站立场,如有内容涉嫌侵权,请联系alex-e#qq.com处理。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3