关于python:快看12种NumpyPandas高效技巧你不看就亏了

1次阅读

共计 5306 个字符,预计需要花费 14 分钟才能阅读完成。

本文分享给大家 12 种 Numpy 和 Pandas 函数,这些高效的函数会令数据分析更为容易、便捷 。最初,读者也能够在 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 函数。

1、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])

2、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

3、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])

4、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])

5、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= <U4 )

6、percentile()

Percentile() 用于计算特定轴方向上数组元素的第 n 个百分位数。

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

这就是 Numpy 扩大包的 6 种高效函数,置信会为你带来帮忙。接下来看一看 Pandas 数据分析库的 6 种函数。

Pandas 的 6 种高效函数

Pandas 也是一个 Python 包,它提供了疾速、灵便以及具备显著表达能力的数据结构,旨在使解决结构化 (表格化、多维、异构) 和工夫序列数据变得既简略又直观。

Pandas 实用于以下各类数据:

  • 具备异构类型列的表格数据,如 SQL 表或 Excel 表;
  • 有序和无序 (不肯定是固定频率) 的工夫序列数据;
  • 带有行 / 列标签的任意矩阵数据(同构类型或者是异构类型);
  • 其余任意模式的统计数据集。事实上,数据基本不须要标记就能够放入 Pandas 构造中。

1、read_csv(nrows=n)

大多数人都会犯的一个谬误是,在不须要.csv 文件的状况下仍会残缺地读取它。如果一个未知的.csv 文件有 10GB,那么读取整个.csv 文件将会十分不明智,不仅要占用大量内存,还会花很多工夫。咱们须要做的只是从.csv 文件中导入几行,之后依据须要持续导入。

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

2、map()

map() 函数依据相应的输出来映射 Series 的值。用于将一个 Series 中的每个值替换为另一个值,该值可能来自一个函数、也可能来自于一个 dict 或 Series。

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

3、apply()

apply() 容许用户传递函数,并将其利用于 Pandas 序列中的每个值。

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

4、isin()

lsin () 用于过滤数据帧。Isin () 有助于抉择特定列中具备特定(或多个)值的行。

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

5、copy()

Copy () 函数用于复制 Pandas 对象。当一个数据帧调配给另一个数据帧时,如果对其中一个数据帧进行更改,另一个数据帧的值也将产生更改。为了避免这类问题,能够应用 copy () 函数。

# creating sample series 
data = pd.Series([India ,  Pakistan ,  China ,  Mongolia])# Assigning issue that we face
data1= data
# Change a value
data1[0]= USA 
# Also changes value in old dataframe
data# To prevent that, we use
# creating copy of series 
new = data.copy()# assigning new values 
new[1]= Changed value # printing data 
print(new) 
print(data)

6、select_dtypes()

select_dtypes() 的作用是,基于 dtypes 的列返回数据帧列的一个子集。这个函数的参数可设置为蕴含所有领有特定数据类型的列,亦或者设置为排除具备特定数据类型的列。

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

最初,pivot_table() 也是 Pandas 中一个十分有用的函数。如果对 pivot_table() 在 excel 中的应用有所理解,那么就非常容易上手了。

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

table

以上就是我分享的内容,心愿对小伙伴你们可能有帮忙!

喜爱这篇内容的,能够点个赞和关注!你们的必定是我后退的一个能源。

正文完
 0