龙空技术网

小白也能看懂的Pandas实操演示教程(上)

daredevil爱科技 696

前言:

此时我们对“pandas计算峰度”可能比较关心,我们都想要分析一些“pandas计算峰度”的相关资讯。那么小编同时在网上汇集了一些有关“pandas计算峰度””的相关资讯,希望朋友们能喜欢,小伙伴们一起来了解一下吧!

文章来源于AI派 作者AAA奔雷手

今天主要带大家来实操学习下Pandas,因为篇幅原因,分为了两部分,本篇为上。

1 数据结构的简介

pandas中有两类非常重要的数据结构,就是序列Series和数据框DataFrame.Series类似于NumPy中的一维数组,可以使用一维数组的可用函数和方法,而且还可以通过索引标签的方式获取数据,还具有索引的自动对齐功能;DataFrame类似于numpy中的二维数组,同样可以使用numpy数组的函数和方法,还具有一些其它灵活的使用。

1.1 Series的创建 三种方法

通过一维数组创建序列m

import pandas as pdimport numpy as nparr1=np.arange(10)print("数组arr1:",arr1)print("arr1的数据类型:",type(arr1))s1=pd.Series(arr1)print("序列s1:",s1)print("s1的数据类型:",type(s1))
数组arr1: [0 1 2 3 4 5 6 7 8 9]arr1的数据类型: <class 'numpy.ndarray'>序列s1:0 01 12 23 34 45 56 67 78 89 9dtype: int32s1的数据类型: <class 'pandas.core.series.Series'>

通过字典的方式创建序列

dict1={'a':1,'b':2,'c':3,'d':4,'e':5}print("字典dict1:",dict1)print("dict1的数据类型:",type(dict1))s2=pd.Series(dict1)print("序列s2:",s2)print("s2的数据类型:",type(s2))
字典dict1: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}dict1的数据类型: <class 'dict'>序列s2:a 1b 2c 3d 4e 5dtype: int64s2的数据类型: <class 'pandas.core.series.Series'>

通过已有DataFrame创建

由于涉及到了DataFrame的概念,所以等后面介绍了DataFrame之后补充下如何通过已有的DataFrame来创建Series。

1.2 DataFrame的创建 三种方法

通过二维数组创建数据框

print("第一种方法创建DataFrame")arr2=np.array(np.arange(12)).reshape(4,3)print("数组2:",arr2)print("数组2的类型",type(arr2))df1=pd.DataFrame(arr2)print("数据框1:",df1)print("数据框1的类型:",type(df1))
第一种方法创建DataFrame数组2: [[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11]]数组2的类型 <class 'numpy.ndarray'>数据框1: 0 1 20 0 1 21 3 4 52 6 7 83 9 10 11数据框1的类型: <class 'pandas.core.frame.DataFrame'>

通过字典列表的方式创建数据框

print("第二种方法创建DataFrame")dict2={'a':[1,2,3,4],'b':[5,6,7,8],'c':[9,10,11,12],'d':[13,14,15,16]}print("字典2-字典列表:",dict2)print("字典2的类型",type(dict2))df2=pd.DataFrame(dict2)print("数据框2:",df2)print("数据框2的类型:",type(df2))
第二种方法创建DataFrame字典2-字典列表: {'a': [1, 2, 3, 4], 'b': [5, 6, 7, 8], 'c': [9, 10, 11, 12], 'd': [13, 14, 15, 16]}字典2的类型 <class 'dict'>数据框2: a b c d0 1 5 9 131 2 6 10 142 3 7 11 153 4 8 12 16数据框2的类型: <class 'pandas.core.frame.DataFrame'>

通过嵌套字典的方式创建数据框

dict3={'one':{'a':1,'b':2,'c':3,'d':4}, 'two':{'a':5,'b':6,'c':7,'d':8}, 'three':{'a':9,'b':10,'c':11,'d':12}}print("字典3-嵌套字典:",dict3)print("字典3的类型",type(dict3))df3=pd.DataFrame(dict3)print("数据框3:",df3)print("数据框3的类型:",type(df3))
字典3-嵌套字典: {'one': {'a': 1, 'b': 2, 'c': 3, 'd': 4}, 'two': {'a': 5, 'b': 6, 'c': 7, 'd': 8}, 'three': {'a': 9, 'b': 10, 'c': 11, 'd': 12}}字典3的类型 <class 'dict'>数据框3: one three twoa 1 9 5b 2 10 6c 3 11 7d 4 12 8数据框3的类型: <class 'pandas.core.frame.DataFrame'>

有了DataFrame之后,这里补充下如何通过DataFrame来创建Series。

s3=df3['one'] #直接拿出数据框3中第一列print("序列3:",s3)print("序列3的类型:",type(s3))print("------------------------------------------------")s4=df3.iloc[0] #df3['a'] #直接拿出数据框3中第一行--ilocprint("序列4:",s4)print("序列4的类型:",type(s4))
序列3: a 1b 2c 3d 4Name: one, dtype: int64序列3的类型: <class 'pandas.core.series.Series'>------------------------------------------------序列4: one 1three 9two 5Name: a, dtype: int64序列4的类型: <class 'pandas.core.series.Series'>

2 数据索引index

无论数据框还是序列,最左侧始终有一个非原始数据对象,这个就是接下来要介绍的数据索引。通过索引获取目标数据,对数据进行一系列的操作。

2.1 通过索引值或索引标签获取数据

s5=pd.Series(np.array([1,2,3,4,5,6]))print(s5) #如果不给序列一个指定索引值,序列会自动生成一个从0开始的自增索引
0 11 22 33 44 55 6dtype: int32

通过index属性获取序列的索引值

s5.index 
RangeIndex(start=0, stop=6, step=1)

为index重新赋值

s5.index=['a','b','c','d','e','f'] s5
a 1b 2c 3d 4e 5f 6dtype: int32

通过索引获取数据

s5[3]4
s5['e']5
s5[[1,3,5]]b 2d 4f 6dtype: int32
s5[:4]a 1b 2c 3d 4dtype: int32
s5['c':]c 3d 4e 5f 6dtype: int32
s5['b':'e'] #通过索引标签获取数据,末端标签的数据也是返回的,b 2c 3d 4e 5dtype: int32

2.2 自动化对齐

#当对两个s6=pd.Series(np.array([10,15,20,30,55,80]),index=['a','b','c','d','e','f'])print("序列6:",s6)s7=pd.Series(np.array([12,11,13,15,14,16]),index=['a','c','g','b','d','f'])print("序列7:",s7)print(s6+s7) #s6中不存在g索引,s7中不存在e索引,所以数据运算会产生两个缺失值NaN。#可以注意到这里的算术运算自动实现了两个序列的自动对齐#对于数据框的对齐,不仅是行索引的自动对齐,同时也会对列索引进行自动对齐,数据框相当于二维数组的推广print(s6/s7)
序列6: a 10b 15c 20d 30e 55f 80dtype: int32序列7: a 12c 11g 13b 15d 14f 16dtype: int32a 22.0b 30.0c 31.0d 44.0e NaNf 96.0g NaNdtype: float64a 0.833333b 1.000000c 1.818182d 2.142857e NaNf 5.000000g NaNdtype: float64

3 pandas查询数据

通过布尔索引有针对的选取原数据的子集,指定行,指定列等。

test_data=pd.read_csv('test_set.csv')# test_data.drop(['ID'],inplace=True,axis=1)test_data.head()

非数值值特征数值化

test_data['job'],jnum=pd.factorize(test_data['job'])test_data['job']=test_data['job']+1test_data['marital'],jnum=pd.factorize(test_data['marital'])test_data['marital']=test_data['marital']+1test_data['education'],jnum=pd.factorize(test_data['education'])test_data['education']=test_data['education']+1test_data['default'],jnum=pd.factorize(test_data['default'])test_data['default']=test_data['default']+1test_data['housing'],jnum=pd.factorize(test_data['housing'])test_data['housing']=test_data['housing']+1test_data['loan'],jnum=pd.factorize(test_data['loan'])test_data['loan']=test_data['loan']+1test_data['contact'],jnum=pd.factorize(test_data['contact'])test_data['contact']=test_data['contact']+1test_data['month'],jnum=pd.factorize(test_data['month'])test_data['month']=test_data['month']+1test_data['poutcome'],jnum=pd.factorize(test_data['poutcome'])test_data['poutcome']=test_data['poutcome']+1test_data.head()

查询数据的前5行

test_data.head()

查询数据的末尾5行

test_data.tail()

查询指定的行

test_data.iloc[[0,2,4,5,7]]

查询指定的列

test_data[['age','job','marital']].head() 

查询指定的行和列

test_data.loc[[0,2,4,5,7],['age','job','marital']]

查询年龄为51的信息

#通过布尔索引实现数据的自己查询test_data[test_data['age']==51].head()

查询工作为5以上的年龄在51的信息

test_data[(test_data['age']==51) & (test_data['job']>=5)].head()

查询工作为5以上,年龄在51的人员,并且只选取指定列

#只选取housing,loan,contac和poutcometest_data[(test_data['age']==51) & (test_data['job']>=5)][['education','housing','loan','contact','poutcome']].head()

可以看到,当有多个条件的查询,需要在&或者|的两端的条件括起来

4 对DataFrames进行统计分析

Pandas为我们提供了很多描述性统计分析的指标函数,包括,总和,均值,最小值,最大值等。

a=np.random.normal(size=10)d1=pd.Series(2*a+3)d2=np.random.f(2,4,size=10)d3=np.random.randint(1,100,size=10)print(d1)print(d2)print(d3)
0 5.8110771 2.9634182 2.2950783 0.2796474 6.5642935 1.1464556 1.9036237 1.1577108 2.9213049 2.397009dtype: float64[0.18147396 0.48218962 0.42565903 0.10258942 0.55299842 0.10859328 0.66923199 1.18542009 0.12053079 4.64172891][33 17 71 45 33 83 68 41 69 23]

非空元素的计算

d1.count() 10

最小值

d1.min() 0.6149265534311872

最大值

d1.max() 6.217953512253818

最小值的位置

d1.idxmin() 8

最大值的位置

d1.idxmax()1

10%分位数

d1.quantile(0.1) 1.4006153623854274

求和

d1.sum() 27.43961378467516

平均数

d1.mean() 2.743961378467515

中位数

d1.median() 2.3460435427041384

众数

d1.mode() 0 0.2796471 1.1464552 1.1577103 1.9036234 2.2950785 2.3970096 2.9213047 2.9634188 5.8110779 6.564293dtype: float64

方差

d1.var() 4.027871738323722

标准差

d1.std() 2.0069558386580715

平均绝对偏差

d1.mad() 1.456849211331346

偏度

d1.skew() 1.0457755613918738

峰度

d1.kurt() 0.39322767370407874

一次性输出多个描述性统计指标

d1.describe() count 10.000000mean 2.743961std 2.006956min 0.27964725% 1.34418950% 2.34604475% 2.952890max 6.564293dtype: float64
#自定义一个函数,将这些统计描述指标全部汇总到一起def stats(x): return pd.Series([x.count(),x.min(),x.idxmin(),x.quantile(.25),x.median(), x.quantile(.75),x.mean(),x.max(),x.idxmax(),x.mad(),x.var(),x.std(),x.skew(),x.kurt()], index=['Count','Min','Which_Min','Q1','Median','Q3','Mean','Max','Which_Max','Mad','Var','Std','Skew', 'Kurt'])
stats(d1)Count 10.000000Min 0.279647Which_Min 3.000000Q1 1.344189Median 2.346044Q3 2.952890Mean 2.743961Max 6.564293Which_Max 4.000000Mad 1.456849Var 4.027872Std 2.006956Skew 1.045776Kurt 0.393228dtype: float64

对于数字型数据,它是直接统计一些数据性描述,观察这一系列数据的范围。大小、波动趋势,便于判断后续对数据采取哪类模型更合适。

#当实际工作中我们需要处理的是一系列的数值型数据框,可以使用apply函数将这个stats函数应用到数据框中的每一列df=pd.DataFrame(np.array([d1,d2,d3]).T,columns=['x1','x2','x3']) #将之前创建的d1,d2,d3数据构建数据框print(df.head())df.apply(stats)
 x1 x2 x30 5.811077 0.181474 33.01 2.963418 0.482190 17.02 2.295078 0.425659 71.03 0.279647 0.102589 45.04 6.564293 0.552998 33.0

以上很简单的创建了数值型数据的统计性描述,但对于离散型数据就不能使用该方法了。我们在统计离散变量的观测数、唯一值个数、众数水平及个数,只需要使用describe方法就可以实现这样的统计了。

train_data=pd.read_csv('train_set.csv')# test_data.drop(['ID'],inplace=True,axis=1)train_data.head()
train_data['job'].describe() #离散型数据的描述count 25317unique 12top blue-collarfreq 5456Name: job, dtype: objecttest_data['job'].describe() #数值型数据的描述count 10852.000000mean 5.593255std 2.727318min 1.00000025% 3.00000050% 6.00000075% 8.000000max 12.000000Name: job, dtype: float64

除了以上简单的描述性统计之外,还提供了连续变量的相关系数(corr)和协方差(cov)的求解

df
 df.corr() #相关系数的计算方法可以调用pearson方法、kendall方法、或者spearman方法,默认使用的是pearson方法
df.corr('spearman')
df.corr('pearson')
df.corr('kendall')
#如果只关注某一个变量与其余变量的相关系数的话,可以使用corrwith,如下方只关注x1与其余变量的相关系数df.corrwith(df['x1'])x1 1.000000x2 -0.075466x3 -0.393609dtype: float64#数值型变量间的协方差矩阵df.cov()

最后,我自己是一名从事了多年开发的Python老程序员,辞职目前在做自己的Python私人定制课程,今年年初我花了一个月整理了一份最适合2019年学习的Python学习干货,可以送给每一位喜欢Python的小伙伴,想要获取的可以关注我的头条号并在后台私信我:01,即可免费获取。

标签: #pandas计算峰度