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

让我们从NumPy开始
NumPy是和N函数使用Python进行科学计算的基本软件包。它包含以下内容:
强大的个惊N维数组对象 复杂的(广播)功能 集成C / C++和Fortran代码的工具 有用的线性代数,傅立叶变换和随机数功能 除了其明显的和N函数科学用途外,NumPy还可以用作通用数据的个惊高效多维容器。可以定义任意数据类型。和N函数这使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非常适合许多不同类型的数据:
具有异构类型列的表格数据,例如在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文件中导入几行,然后根据需要继续操作。
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 weve 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返回数据框的列的子集。可以将此函数的参数设置为包括具有某些特定数据类型的所有列,也可以将其设置为排除具有某些特定数据类型的所有那些列。
# Well 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 Jupyter Notebook(使用代码)可以从以下链接找到:
https://github.com/kunaldhariwal/Medium-12-Amazing-Pandas-NumPy-Functions