12个很棒的Pandas和NumPy函数,让解析事半功倍
感谢作者分享-http://bjbsair.com/2020-04-07/tech-info/30428.html
大家都知道Pandas和NumPy函数很棒,它们在日常分析中起着重要的作用。没有这两个函数,人们将在这个庞大的数据分析和科学世界中迷失方向。
今天,分享12个很棒的Pandas和NumPy函数,这些函数将会让生活更便捷,让分析事半功倍。
在本文结尾,读者可以找到文中提到的代码的JupyterNotebook。
从NumPy开始:
NumPy是使用Python进行科学计算的基本软件包。它包含以下内容:
· 强大的N维数组对象
· 复杂的(广播broadcasting)功能
· 集成C / C++和Fortran代码工具
· 有用的线性代数,傅立叶变换和随机数功能
除明显的科学用途外,NumPy是高效的通用数据多维容器,可以定义任意数据类型。这使NumPy能够无缝且高速地与各种数据库进行集成。
1. 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 shouldreturn 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
2. 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])
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() 函数用于根据特定条件从数组中提取特定元素。有了该函数,还可以使用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 ifremainder 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])# Applycondition on extract directly
np.extract(((array < 3) | (array > 15)), array)
array([ 0, 1, 19, 16, 18, 2])
5. percentile()
Percentile()用于计算沿指定轴的数组元素的第n个百分位数。
a = np.array([1,5,6,8,1,7,3,6,9])print("50thPercentile 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.13.5 1.9]
6. where()
Where() 用于从满足特定条件的数组中返回元素。它返回在特定条件下值的索引位置。这差不多类似于在SQL中使用的where语句。请看以下示例中的演示。
y = np.array([1,5,6,8,1,7,3,6,9])# Where y is greaterthan 5, returns index position
np.where(y>5)
array([2, 3, 5, 7, 8], dtype=int64),)# First will replace the values that matchthe 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')
接着来讲一讲神奇的Pandas函数。
Pandas
Pandas是一个Python软件包,提供快速、灵活和富有表现力的数据结构,旨在使处理结构化(表格,多维,潜在异构)的数据和时间序列数据既简单又直观。
Pandas非常适合许多不同类型的数据:
· 具有异构类型列的表格数据,例如在SQL表或Excel电子表格中
· 有序和无序(不一定是固定频率)的时间序列数据。
· 具有行和列标签的任意矩阵数据(同类型或异类)
· 观察/统计数据集的任何其他形式。实际上,数据根本不需要标记,即可放入Pandas数据结构。
以下是Pandas的优势:
· 轻松处理浮点数据和非浮点数据中的缺失数据(表示为NaN)
· 大小可变性:可以从DataFrame和更高维的对象中插入和删除列
· 自动和显式的数据对齐:在计算中,可以将对象显式对齐到一组标签,或者用户可以直接忽略标签,并让Series,DataFrame等自动对齐数据
· 强大灵活的分组功能,可对数据集执行拆分-应用-合并操作,以汇总和转换数据
· 轻松将其他Python和NumPy数据结构中的不规则的、索引不同的数据转换为DataFrame对象
· 大数据集的智能标签的切片,高级索引和子集化
· 直观的合并和联接数据集
· 数据集的灵活重塑和旋
· 坐标轴的分层标签(每个刻度可能有多个标签)
· 强大的IO工具,用于从平面文件(CSV和定界文件)、 Excel文件,数据库加载数据,以及以超高速HDF5格式保存/加载数据
· 特定于时间序列的功能:日期范围生成和频率转换、移动窗口统计、日期移位和滞后。
1. apply()
Apply() 函数允许用户传递函数并将其应用于Pandas序列中每个单一值。
# max minus mix lambda fn
fn = lambda x: x.max() - x.min()# Apply this on dframe that we've just createdabove
dframe.apply(fn)
2. copy()
Copy()函数用于创建Pandas对象的副本。将数据帧分配给另一个数据帧时,在另一个数据帧中进行更改,其值也会进行同步更改。为了避免出现上述问题,可以使用copy()函数。
# creating sample series
data = pd.Series(['India', 'Pakistan', 'China', 'Mongolia'])# Assigning issuethat 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)
3. 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 foryou 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)
4. map()
map()函数用于根据输入对应关系映射Series的值。用于将序列(Series)中的每个值替换为另一个值,该值可以从函数、字典或序列(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 eachfloating point value in frame
changefn = lambda x: '%.2f' % x# Make changes element-wise
dframe['d'].map(changefn)
5. 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]
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中的工作原理,那么一切就非常简单了。数据透视表中的级别将存贮在MultiIndex对象(分层索引)中,而该对象位于DataFrame结果的索引和列上。
# 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
感谢作者分享-http://bjbsair.com/2020-04-07/tech-info/30428.html
大家都知道Pandas和NumPy函数很棒,它们在日常分析中起着重要的作用。没有这两个函数,人们将在这个庞大的数据分析和科学世界中迷失方向。
今天,分享12个很棒的Pandas和NumPy函数,这些函数将会让生活更便捷,让分析事半功倍。
在本文结尾,读者可以找到文中提到的代码的JupyterNotebook。
从NumPy开始:
NumPy是使用Python进行科学计算的基本软件包。它包含以下内容:
· 强大的N维数组对象
· 复杂的(广播broadcasting)功能
· 集成C / C++和Fortran代码工具
· 有用的线性代数,傅立叶变换和随机数功能
除明显的科学用途外,NumPy是高效的通用数据多维容器,可以定义任意数据类型。这使NumPy能够无缝且高速地与各种数据库进行集成。
1. 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 shouldreturn 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
2. 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])
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() 函数用于根据特定条件从数组中提取特定元素。有了该函数,还可以使用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 ifremainder 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])# Applycondition on extract directly
np.extract(((array < 3) | (array > 15)), array)
array([ 0, 1, 19, 16, 18, 2])
5. percentile()
Percentile()用于计算沿指定轴的数组元素的第n个百分位数。
a = np.array([1,5,6,8,1,7,3,6,9])print("50thPercentile 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.13.5 1.9]
6. where()
Where() 用于从满足特定条件的数组中返回元素。它返回在特定条件下值的索引位置。这差不多类似于在SQL中使用的where语句。请看以下示例中的演示。
y = np.array([1,5,6,8,1,7,3,6,9])# Where y is greaterthan 5, returns index position
np.where(y>5)
array([2, 3, 5, 7, 8], dtype=int64),)# First will replace the values that matchthe 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')
接着来讲一讲神奇的Pandas函数。
Pandas
Pandas是一个Python软件包,提供快速、灵活和富有表现力的数据结构,旨在使处理结构化(表格,多维,潜在异构)的数据和时间序列数据既简单又直观。
Pandas非常适合许多不同类型的数据:
· 具有异构类型列的表格数据,例如在SQL表或Excel电子表格中
· 有序和无序(不一定是固定频率)的时间序列数据。
· 具有行和列标签的任意矩阵数据(同类型或异类)
· 观察/统计数据集的任何其他形式。实际上,数据根本不需要标记,即可放入Pandas数据结构。
以下是Pandas的优势:
· 轻松处理浮点数据和非浮点数据中的缺失数据(表示为NaN)
· 大小可变性:可以从DataFrame和更高维的对象中插入和删除列
· 自动和显式的数据对齐:在计算中,可以将对象显式对齐到一组标签,或者用户可以直接忽略标签,并让Series,DataFrame等自动对齐数据
· 强大灵活的分组功能,可对数据集执行拆分-应用-合并操作,以汇总和转换数据
· 轻松将其他Python和NumPy数据结构中的不规则的、索引不同的数据转换为DataFrame对象
· 大数据集的智能标签的切片,高级索引和子集化
· 直观的合并和联接数据集
· 数据集的灵活重塑和旋
· 坐标轴的分层标签(每个刻度可能有多个标签)
· 强大的IO工具,用于从平面文件(CSV和定界文件)、 Excel文件,数据库加载数据,以及以超高速HDF5格式保存/加载数据
· 特定于时间序列的功能:日期范围生成和频率转换、移动窗口统计、日期移位和滞后。
1. apply()
Apply() 函数允许用户传递函数并将其应用于Pandas序列中每个单一值。
# max minus mix lambda fn
fn = lambda x: x.max() - x.min()# Apply this on dframe that we've just createdabove
dframe.apply(fn)
2. copy()
Copy()函数用于创建Pandas对象的副本。将数据帧分配给另一个数据帧时,在另一个数据帧中进行更改,其值也会进行同步更改。为了避免出现上述问题,可以使用copy()函数。
# creating sample series
data = pd.Series(['India', 'Pakistan', 'China', 'Mongolia'])# Assigning issuethat 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)
3. 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 foryou 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)
4. map()
map()函数用于根据输入对应关系映射Series的值。用于将序列(Series)中的每个值替换为另一个值,该值可以从函数、字典或序列(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 eachfloating point value in frame
changefn = lambda x: '%.2f' % x# Make changes element-wise
dframe['d'].map(changefn)
5. 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]
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中的工作原理,那么一切就非常简单了。数据透视表中的级别将存贮在MultiIndex对象(分层索引)中,而该对象位于DataFrame结果的索引和列上。
# 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
感谢作者分享-http://bjbsair.com/2020-04-07/tech-info/30428.html
大家都知道Pandas和NumPy函数很棒,它们在日常分析中起着重要的作用。没有这两个函数,人们将在这个庞大的数据分析和科学世界中迷失方向。
今天,分享12个很棒的Pandas和NumPy函数,这些函数将会让生活更便捷,让分析事半功倍。
在本文结尾,读者可以找到文中提到的代码的JupyterNotebook。
从NumPy开始:
NumPy是使用Python进行科学计算的基本软件包。它包含以下内容:
· 强大的N维数组对象
· 复杂的(广播broadcasting)功能
· 集成C / C++和Fortran代码工具
· 有用的线性代数,傅立叶变换和随机数功能
除明显的科学用途外,NumPy是高效的通用数据多维容器,可以定义任意数据类型。这使NumPy能够无缝且高速地与各种数据库进行集成。
1. 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 shouldreturn 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
2. 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])
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() 函数用于根据特定条件从数组中提取特定元素。有了该函数,还可以使用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 ifremainder 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])# Applycondition on extract directly
np.extract(((array < 3) | (array > 15)), array)
array([ 0, 1, 19, 16, 18, 2])
5. percentile()
Percentile()用于计算沿指定轴的数组元素的第n个百分位数。
a = np.array([1,5,6,8,1,7,3,6,9])print("50thPercentile 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.13.5 1.9]
6. where()
Where() 用于从满足特定条件的数组中返回元素。它返回在特定条件下值的索引位置。这差不多类似于在SQL中使用的where语句。请看以下示例中的演示。
y = np.array([1,5,6,8,1,7,3,6,9])# Where y is greaterthan 5, returns index position
np.where(y>5)
array([2, 3, 5, 7, 8], dtype=int64),)# First will replace the values that matchthe 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')
接着来讲一讲神奇的Pandas函数。
Pandas
Pandas是一个Python软件包,提供快速、灵活和富有表现力的数据结构,旨在使处理结构化(表格,多维,潜在异构)的数据和时间序列数据既简单又直观。
Pandas非常适合许多不同类型的数据:
· 具有异构类型列的表格数据,例如在SQL表或Excel电子表格中
· 有序和无序(不一定是固定频率)的时间序列数据。
· 具有行和列标签的任意矩阵数据(同类型或异类)
· 观察/统计数据集的任何其他形式。实际上,数据根本不需要标记,即可放入Pandas数据结构。
以下是Pandas的优势:
· 轻松处理浮点数据和非浮点数据中的缺失数据(表示为NaN)
· 大小可变性:可以从DataFrame和更高维的对象中插入和删除列
· 自动和显式的数据对齐:在计算中,可以将对象显式对齐到一组标签,或者用户可以直接忽略标签,并让Series,DataFrame等自动对齐数据
· 强大灵活的分组功能,可对数据集执行拆分-应用-合并操作,以汇总和转换数据
· 轻松将其他Python和NumPy数据结构中的不规则的、索引不同的数据转换为DataFrame对象
· 大数据集的智能标签的切片,高级索引和子集化
· 直观的合并和联接数据集
· 数据集的灵活重塑和旋
· 坐标轴的分层标签(每个刻度可能有多个标签)
· 强大的IO工具,用于从平面文件(CSV和定界文件)、 Excel文件,数据库加载数据,以及以超高速HDF5格式保存/加载数据
· 特定于时间序列的功能:日期范围生成和频率转换、移动窗口统计、日期移位和滞后。
1. apply()
Apply() 函数允许用户传递函数并将其应用于Pandas序列中每个单一值。
# max minus mix lambda fn
fn = lambda x: x.max() - x.min()# Apply this on dframe that we've just createdabove
dframe.apply(fn)
2. copy()
Copy()函数用于创建Pandas对象的副本。将数据帧分配给另一个数据帧时,在另一个数据帧中进行更改,其值也会进行同步更改。为了避免出现上述问题,可以使用copy()函数。
# creating sample series
data = pd.Series(['India', 'Pakistan', 'China', 'Mongolia'])# Assigning issuethat 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)
3. 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 foryou 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)
4. map()
map()函数用于根据输入对应关系映射Series的值。用于将序列(Series)中的每个值替换为另一个值,该值可以从函数、字典或序列(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 eachfloating point value in frame
changefn = lambda x: '%.2f' % x# Make changes element-wise
dframe['d'].map(changefn)
5. 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]
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中的工作原理,那么一切就非常简单了。数据透视表中的级别将存贮在MultiIndex对象(分层索引)中,而该对象位于DataFrame结果的索引和列上。
# 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
感谢作者分享-http://bjbsair.com/2020-04-07/tech-info/30428.html
大家都知道Pandas和NumPy函数很棒,它们在日常分析中起着重要的作用。没有这两个函数,人们将在这个庞大的数据分析和科学世界中迷失方向。
今天,分享12个很棒的Pandas和NumPy函数,这些函数将会让生活更便捷,让分析事半功倍。
在本文结尾,读者可以找到文中提到的代码的JupyterNotebook。
从NumPy开始:
NumPy是使用Python进行科学计算的基本软件包。它包含以下内容:
· 强大的N维数组对象
· 复杂的(广播broadcasting)功能
· 集成C / C++和Fortran代码工具
· 有用的线性代数,傅立叶变换和随机数功能
除明显的科学用途外,NumPy是高效的通用数据多维容器,可以定义任意数据类型。这使NumPy能够无缝且高速地与各种数据库进行集成。
1. 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 shouldreturn 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
2. 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])
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() 函数用于根据特定条件从数组中提取特定元素。有了该函数,还可以使用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 ifremainder 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])# Applycondition on extract directly
np.extract(((array < 3) | (array > 15)), array)
array([ 0, 1, 19, 16, 18, 2])
5. percentile()
Percentile()用于计算沿指定轴的数组元素的第n个百分位数。
a = np.array([1,5,6,8,1,7,3,6,9])print("50thPercentile 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.13.5 1.9]
6. where()
Where() 用于从满足特定条件的数组中返回元素。它返回在特定条件下值的索引位置。这差不多类似于在SQL中使用的where语句。请看以下示例中的演示。
y = np.array([1,5,6,8,1,7,3,6,9])# Where y is greaterthan 5, returns index position
np.where(y>5)
array([2, 3, 5, 7, 8], dtype=int64),)# First will replace the values that matchthe 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')
接着来讲一讲神奇的Pandas函数。
Pandas
Pandas是一个Python软件包,提供快速、灵活和富有表现力的数据结构,旨在使处理结构化(表格,多维,潜在异构)的数据和时间序列数据既简单又直观。
Pandas非常适合许多不同类型的数据:
· 具有异构类型列的表格数据,例如在SQL表或Excel电子表格中
· 有序和无序(不一定是固定频率)的时间序列数据。
· 具有行和列标签的任意矩阵数据(同类型或异类)
· 观察/统计数据集的任何其他形式。实际上,数据根本不需要标记,即可放入Pandas数据结构。
以下是Pandas的优势:
· 轻松处理浮点数据和非浮点数据中的缺失数据(表示为NaN)
· 大小可变性:可以从DataFrame和更高维的对象中插入和删除列
· 自动和显式的数据对齐:在计算中,可以将对象显式对齐到一组标签,或者用户可以直接忽略标签,并让Series,DataFrame等自动对齐数据
· 强大灵活的分组功能,可对数据集执行拆分-应用-合并操作,以汇总和转换数据
· 轻松将其他Python和NumPy数据结构中的不规则的、索引不同的数据转换为DataFrame对象
· 大数据集的智能标签的切片,高级索引和子集化
· 直观的合并和联接数据集
· 数据集的灵活重塑和旋
· 坐标轴的分层标签(每个刻度可能有多个标签)
· 强大的IO工具,用于从平面文件(CSV和定界文件)、 Excel文件,数据库加载数据,以及以超高速HDF5格式保存/加载数据
· 特定于时间序列的功能:日期范围生成和频率转换、移动窗口统计、日期移位和滞后。
1. apply()
Apply() 函数允许用户传递函数并将其应用于Pandas序列中每个单一值。
# max minus mix lambda fn
fn = lambda x: x.max() - x.min()# Apply this on dframe that we've just createdabove
dframe.apply(fn)
2. copy()
Copy()函数用于创建Pandas对象的副本。将数据帧分配给另一个数据帧时,在另一个数据帧中进行更改,其值也会进行同步更改。为了避免出现上述问题,可以使用copy()函数。
# creating sample series
data = pd.Series(['India', 'Pakistan', 'China', 'Mongolia'])# Assigning issuethat 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)
3. 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 foryou 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)
4. map()
map()函数用于根据输入对应关系映射Series的值。用于将序列(Series)中的每个值替换为另一个值,该值可以从函数、字典或序列(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 eachfloating point value in frame
changefn = lambda x: '%.2f' % x# Make changes element-wise
dframe['d'].map(changefn)
5. 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]
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中的工作原理,那么一切就非常简单了。数据透视表中的级别将存贮在MultiIndex对象(分层索引)中,而该对象位于DataFrame结果的索引和列上。
# 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
12个很棒的Pandas和NumPy函数,让解析事半功倍相关推荐
- 12个很棒的Pandas和NumPy函数,让python数据分析事半功倍
大家都知道Pandas和NumPy函数很棒,它们在日常分析中起着重要的作用.没有这两个函数,人们将在这个庞大的数据分析和科学世界中迷失方向. 今天,小芯将分享12个很棒的Pandas和NumPy函数, ...
- numpy序列预处理dna序列_?12个很棒的Pandas和NumPy函数,让分析事半功倍
全文共5431字,预计学习时长16分钟 来源:Pexels 大家都知道Pandas和NumPy函数很棒,它们在日常分析中起着重要的作用.没有这两个函数,人们将在这个庞大的数据分析和科学世界中迷失方向. ...
- 12个很棒的Pandas和NumPy函数,让分析事半功倍
全文共5431字,预计学习时长16分钟 来源:Pexels 大家都知道Pandas和NumPy函数很棒,它们在日常分析中起着重要的作用.没有这两个函数,人们将在这个庞大的数据分析和科学世界中迷失方向. ...
- panda python_12个很棒的Pandas和NumPy函数,让分析事半功倍
本文转载自公众号"读芯术"(ID:AI_Discovery) 大家都知道Pandas和NumPy函数很棒,它们在日常分析中起着重要的作用.没有这两个函数,人们将在这个庞大的数据分析 ...
- 12个很棒的学习 jQuery 的网站推荐
原文地址为: 12个很棒的学习 jQuery 的网站推荐 jQuery是目前最流行的 JavaScript 库.对于初学者来说,有的时候很难找到一个好的学习jQuery的网站,今天本文收集了12个很棒 ...
- 12个很棒的Spring数据教程来启动您的数据项目
Spring Data的任务是为数据访问提供一个熟悉且一致的,基于Spring的编程模型,同时仍保留基础数据存储的特殊特征. 它使使用数据访问技术,关系和非关系数据库,map-reduce框架以及 ...
- 12款很棒的浏览器兼容性测试工具
对于前端开发工程师来说,确保代码在各种主流浏览器的各个版本中都能正常工作是件很费时的事情,幸运的是,有很多优秀的工具可以帮助测试浏览器的兼容性,让我们一起看看这些很棒的工具. Spoon Browse ...
- 12款很棒的浏览器兼容性测试工具推荐
对于前端开发工程师来说,确保代码在各种主流浏览器的各个版本中都能正常工作是件很费时的事情,幸运的是,有很多优秀的工具可以帮助测试浏览器的兼容性,让我们一起看看这些很棒的工具. Spoon Browse ...
- 12 个 Pandas Numpy 函数:数据分析提速 50% 不是问题!
关注"迈微AI研习社",内容首发于公众号 作者:Kunal Dhariwal 我们都知道,Numpy 是 Python 环境下的扩展程序库,支持大量的维度数组和矩阵运算:Panda ...
最新文章
- python爬取电影和美食数据实战
- VHDL+Verilog良好的代码编写风格(转载)
- 海量数据库及分区4——《12年资深DBA教你Oracle开发与优化——性能优化部分》...
- 【转】Windows8不联网直接安装.Net 3.5 Framework的方法
- C++primer CH12智能指针
- 使用代码获得Hybris Commerce里显示的产品图片
- 邮件服务器之POP3协议分析
- 【安装包】MySQL客户端
- 30.磁盘 I/O 问题
- sklearn中的降维算法(PCA)(原理相关)-1
- Atitit mybatis的扩展使用sql udf,js java等语言 目录 1.1. 默认,mybatis使用xml,sql等语言来书写业务流程	1 2. 使用java扩展函数	1 2.1.
- 解决方案架构师的职责
- java在线编辑word_java web实现在线编辑word,并将word导出(一)
- 中国占三分之一!CBinsights世界最新独角兽排名出炉
- JsonMappingException: Problem deserializing 'setterless' property '': get method returned null
- 微型计算机主频一般为,【单选题】目前使用的微型计算机的主频一般为________。
A. 2.6GHz B. 256MHz C. 2.3THz D. 900Hz...
- 计算机中的栈的模板,栈类模板实现含界面.doc
- SSH综合项目实战(快递) -- day07 定区关联快递员、搭建前台、客户注册
- python下载是免费的吗-关于python下载imooc的免费视频的方法
- QTextEdit详解
热门文章
- 金融理财直播大热,机构各出奇招
- 人工智能如何为传统产业赋能?| 活动
- java读取pi_java读取PI数据库测点值
- JavaScript中switch语句的参数问题
- python实现lfm_【知识发现】隐语义模型(LFM,Latent Factor Model)推荐算法python实现
- eclipse注释里面中文字大小不一致解决办法。eclipse注释里面数字后中文字号变大解决办法。eclipse注释里面符号后字体变小的方法。调成中欧字符仍然没用解决方案
- 花一千多学python值吗_Python爬虫应该怎么学?程序猿花了一周整理的学习技巧,请收下...
- 电脑接html线没反应,iphone数据线接电脑没反应的处理方法:
- #0005 JPA Querydsl无法生成Q类
- layer.js 方法