Pandas和NumPy函数的使用方法有哪些

发布时间:2021-11-05 11:49:56 作者:iii
来源:亿速云 阅读:186

本篇内容主要讲解“Pandas和NumPy函数的使用方法有哪些”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Pandas和NumPy函数的使用方法有哪些”吧!

1. argpartition()

NumPy具有此惊人的功能,可以找到N个最大值索引。输出将是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()用于匹配两个数组并以布尔值形式获取输出。如果两个数组中的项在公差范围内不相等,则将返回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()。给定一个间隔,该间隔以外的值将被裁剪到间隔边缘。

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

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.0 b = 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]

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

pandas:

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

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

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

1. read_csv(nrows = n)

您可能已经知道read_csv函数的使用。但是,即使不需要,我们大多数人仍然会错误地读取整个.csv文件。让我们考虑一种情况,即我们不知道10gb的.csv文件中的列和数据,在这里读取整个.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的值。用于将系列中的每个值替换为另一个值,该值可以从函数,字典或系列中得出。

# 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()

isin()用于过滤数据帧。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 datadata1= 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。如果您犹豫使用groupby并想扩展其功能,那么可以很好地使用pivot_table。如果您知道数据透视表在excel中是如何工作的,那么对您来说可能只是小菜一碟。数据透视表中的级别将存储在结果DataFrame的索引和列上的MultiIndex对象(分层索引)中。

# 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

到此,相信大家对“Pandas和NumPy函数的使用方法有哪些”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

推荐阅读:
  1. python中numpy和pandas介绍
  2. Pandas Series和Numpy array中的相同点有哪些

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

pandas numpy

上一篇:怎么在微信小程序中使用async/await

下一篇:Java的执行原理是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》