12个惊人的Pandas和NumPy函数

开发 前端
今天,我将分享12个惊人的Pandas和NumPy函数,这些函数将使您的生活和分析变得比以前容易得多。 最后,您可以找到本文所用代码的Jupyter Notebook。

我们都知道Pandas和NumPy很棒,它们在我们的日常分析中起着至关重要的作用。没有Pandas和NumPy,我们将在这个庞大的数据分析和科学世界中迷茫。今天,我将分享12个惊人的Pandas和NumPy函数,这些函数将使您的生活和分析变得比以前容易得多。 最后,您可以找到本文所用代码的Jupyter Notebook。

12个惊人的Pandas和NumPy函数

让我们从NumPy开始

NumPy是使用Python进行科学计算的基本软件包。它包含以下内容:

  • 强大的N维数组对象
  • 复杂的(广播)功能
  • 集成C / C++和Fortran代码的工具
  • 有用的线性代数,傅立叶变换和随机数功能

除了其明显的科学用途外,NumPy还可以用作通用数据的高效多维容器。可以定义任意数据类型。这使NumPy能够无缝,快速地与各种数据库集成。

1. argpartition()

NumPy具有此惊人的功能,可以找到N个最大值索引。输出将是N个最大值索引,然后可以根据需要对值进行排序。

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

2. allclose()

Allclose()用于匹配两个数组并以布尔值形式获取输出。如果两个数组中的项在公差范围内不相等,则将返回False。这是检查两个数组是否相似的好方法,这实际上很难手动实现。

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

3. clip()

Clip()用于将值保留在一个间隔内的数组中。有时,我们需要将值保持在上限和下限之内。出于上述目的,我们可以使用NumPy的clip()。给定一个间隔,该间隔以外的值将被裁剪到间隔边缘。

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

4. extract()

顾名思义,Extract()用于根据特定条件从数组中提取特定元素。通过extract(),我们还可以使用诸如and和 or的条件。

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

5. where()

where()用于从满足特定条件的数组中返回元素。它返回在特定条件下的值的索引位置。这几乎类似于我们在SQL中使用的where条件,我将在下面的示例中进行演示。

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

6. percentile()

Percentile()用于计算沿指定轴的数组元素的第n个百分点。

  1. a = np.array([1,5,6,8,1,7,3,6,9]) 
  2. print("50th Percentile of a, axis = 0 : ",   
  3.       np.percentile(a, 50, axis =0)) 
  4. 50th Percentile of a, axis = 0 :  6.0 
  5. b = np.array([[10, 7, 4], [3, 2, 1]]) 
  6. print("30th Percentile of b, axis = 0 : ",   
  7.       np.percentile(b, 30, axis =0)) 
  8. 30th Percentile of b, axis = 0 :  [5.1 3.5 1.9] 

如果您以前使用过它们,请就应该能体会到它对您有多大帮助。让我们继续前进到令人惊叹的Pandas。

pandas:

pandas是一个Python软件包,提供快速,灵活和富于表现力的数据结构,旨在使处理结构化(表格,多维,潜在异构)和时间序列数据既简单又直观。

Pandas非常适合许多不同类型的数据:

  • 具有异构类型列的表格数据,例如在SQL表或Excel电子表格中
  • 有序和无序(不一定是固定频率)时间序列数据。
  • 具有行和列标签的任意矩阵数据(同类型或异类)
  • 观察/统计数据集的任何其他形式。实际上,数据根本不需要标记即可放入Pandas数据结构。

以下是Pandas做得好的一些事情:

  • 轻松处理浮点数据和非浮点数据中的缺失数据(表示为NaN)
  • 大小可变性:可以从DataFrame和更高维的对象中插入和删除列
  • 自动和显式的数据对齐:可以将对象显式地对齐到一组标签,或者用户可以简单地忽略标签并让Series,DataFrame等自动为您对齐数据
  • 强大,灵活的分组功能,可对数据集执行拆分应用合并操作,以汇总和转换数据
  • 轻松将其他Python和NumPy数据结构中的衣衫,、索引不同的数据转换为DataFrame对象
  • 基于智能标签的切片,花式索引和大数据集子集
  • 直观的合并和联接数据集
  • 灵活地重塑和旋转数据集
  • 轴的分层标签(每个刻度可能有多个标签)
  • 强大的IO工具,用于从平面文件(CSV和定界文件),Excel文件,数据库加载数据,以及从超快HDF5格式保存/加载数据
  • 特定于时间序列的功能:日期范围生成和频率转换,移动窗口统计信息,日期移动和滞后。

1. read_csv(nrows = n)

您可能已经知道read_csv函数的使用。但是,即使不需要,我们大多数人仍然会错误地读取整个.csv文件。让我们考虑一种情况,即我们不知道10gb的.csv文件中的列和数据,在这里读取整个.csv文件将不是一个明智的决定,因为这将不必要地占用我们的内存,并且会花费很多时间时间。我们可以仅从.csv文件中导入几行,然后根据需要继续操作。

  1. import io 
  2. import requests 
  3. # I am using this online data set just to make things easier for you guys 
  4. url = "https://raw.github.com/vincentarelbundock/Rdatasets/master/csv/datasets/AirPassengers.csv" 
  5. s = requests.get(url).content 
  6. # read only first 10 rows 
  7. df = pd.read_csv(io.StringIO(s.decode('utf-8')),nrows=10 , index_col=0

2. map()

map()函数用于根据输入对应关系映射Series的值。用于将系列中的每个值替换为另一个值,该值可以从函数,字典或系列中得出。

  1. # create a dataframe 
  2. dframe = pd.DataFrame(np.random.randn(4, 3), columns=list('bde'), index=['India', 'USA', 'China', 'Russia']) 
  3. #compute a formatted string from each floating point value in frame 
  4. changefn = lambda x: '%.2f' % x 
  5. # Make changes element-wise 
  6. dframe['d'].map(changefn) 

3. apply()

apply()允许用户传递一个函数并将其应用于Pandas系列的每个单个值。

  1. # max minus mix lambda fn 
  2. fn = lambda x: x.max() - x.min() 
  3. # Apply this on dframe that we've just created above 
  4. dframe.apply(fn) 

4. isin()

isin()用于过滤数据帧。isin()帮助选择在特定列中具有特定(或多个)值的行。这是我遇到的最有用的功能。

  1. # Using the dataframe we created for read_csv 
  2. filter1 = df["value"].isin([112])  
  3. filter2 = df["time"].isin([1949.000000]) 
  4. df [filter1 & filter2] 

5. copy()

copy()用于创建Pandas对象的副本。将数据帧分配给另一个数据帧时,在另一个数据帧中进行更改时其值也会更改。为了防止出现上述问题,我们可以使用copy()。

  1. # creating sample series  
  2. data = pd.Series(['India', 'Pakistan', 'China', 'Mongolia']) 
  3. # Assigning issue that we face 
  4. datadata1= data 
  5. # Change a value 
  6. data1[0]='USA' 
  7. # Also changes value in old dataframe 
  8. data 
  9. # To prevent that, we use 
  10. # creating copy of series  
  11. new = data.copy() 
  12. # assigning new values  
  13. new[1]='Changed value' 
  14. # printing data  
  15. print(new)  
  16. print(data) 

6. select_dtypes()

select_dtypes()函数基于列dtypes返回数据框的列的子集。可以将此函数的参数设置为包括具有某些特定数据类型的所有列,也可以将其设置为排除具有某些特定数据类型的所有那些列。

  1. # We'll use the same dataframe that we used for read_csv 
  2. framex =  df.select_dtypes(include="float64"
  3. # Returns only time column 

额外的奖励:

pivot_table()pandas 最神奇最有用的功能是pivot_table。如果您犹豫使用groupby并想扩展其功能,那么可以很好地使用pivot_table。如果您知道数据透视表在excel中是如何工作的,那么对您来说可能只是小菜一碟。数据透视表中的级别将存储在结果DataFrame的索引和列上的MultiIndex对象(分层索引)中。

  1. # Create a sample dataframe 
  2. school = pd.DataFrame({'A': ['Jay', 'Usher', 'Nicky', 'Romero', 'Will'],  
  3.       'B': ['Masters', 'Graduate', 'Graduate', 'Masters', 'Graduate'],  
  4.       'C': [26, 22, 20, 23, 24]}) 
  5. # Lets create a pivot table to segregate students based on age and course 
  6. table = pd.pivot_table(school, values ='A'index =['B', 'C'], columns =['B'], aggfunc = np.sum, fill_value="Not Available")  
  7.    
  8. table 

Jupyter Notebook(使用代码)可以从以下链接找到:

https://github.com/kunaldhariwal/Medium-12-Amazing-Pandas-NumPy-Functions

 

责任编辑:赵宁宁 来源: 今日头条
相关推荐

2020-04-03 13:50:19

数据分析PandasNumPy

2020-05-06 09:18:56

Pandas函数大数据技术

2024-01-03 14:54:56

PythonPandas数据处理工具

2021-07-07 09:50:23

NumpyPandasPython

2023-09-08 13:11:00

NumPyPandasPython库

2023-07-31 11:44:38

Pandas性能数组

2023-10-15 17:07:35

PandasPython库

2022-07-06 23:59:57

NumPyPython工具

2022-09-20 10:50:34

PandasNumPy

2021-02-19 10:59:29

NumpyPandasPython

2021-07-13 10:02:52

Pandas函数Linux

2023-02-08 17:04:14

Python计算库数学函数

2020-08-16 10:58:20

Pandaspython开发

2023-08-11 11:19:52

数据集Merge函数

2021-05-10 11:40:51

函数NumpyPython

2020-12-24 07:02:07

CSS框架

2020-10-29 08:35:06

Pandas函数Python

2022-07-06 06:17:51

PandasScipynumpy

2012-06-14 13:22:35

JavaScript

2023-02-07 16:21:37

时间序列列数据集
点赞
收藏

51CTO技术栈公众号