首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >小白也能看懂的Pandas实操演示教程(上)

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

作者头像
1480
发布2019-09-25 16:32:27
1.3K0
发布2019-09-25 16:32:27
举报
文章被收录于专栏:数据分析1480数据分析1480

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

1 数据结构的简介

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

1.1 Series的创建 三种方法

通过一维数组创建序列m
import pandas as pd
import numpy as np

arr1=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    0
1    1
2    2
3    3
4    4
5    5
6    6
7    7
8    8
9    9
dtype: int32
s1的数据类型: <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    1
b    2
c    3
d    4
e    5
dtype: int64
s2的数据类型: <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   2
0  0   1   2
1  3   4   5
2  6   7   8
3  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   d
0  1  5   9  13
1  2  6  10  14
2  3  7  11  15
3  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  two
a    1      9    5
b    2     10    6
c    3     11    7
d    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中第一行--iloc
print("序列4:
",s4)
print("序列4的类型:",type(s4))

序列3:
 a    1
b    2
c    3
d    4
Name: one, dtype: int64
序列3的类型: <class 'pandas.core.series.Series'>
------------------------------------------------
序列4:
 one      1
three    9
two      5
Name: 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    1
1    2
2    3
3    4
4    5
5    6
dtype: int32
通过index属性获取序列的索引值
s5.index 

RangeIndex(start=0, stop=6, step=1)
为index重新赋值
s5.index=['a','b','c','d','e','f'] 
s5

a    1
b    2
c    3
d    4
e    5
f    6
dtype: int32
通过索引获取数据
s5[3]
4

s5['e']
5

s5[[1,3,5]]
b    2
d    4
f    6
dtype: int32

s5[:4]
a    1
b    2
c    3
d    4
dtype: int32

s5['c':]
c    3
d    4
e    5
f    6
dtype: int32

s5['b':'e']  #通过索引标签获取数据,末端标签的数据也是返回的,
b    2
c    3
d    4
e    5
dtype: 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    10
b    15
c    20
d    30
e    55
f    80
dtype: int32
序列7: a    12
c    11
g    13
b    15
d    14
f    16
dtype: int32
a    22.0
b    30.0
c    31.0
d    44.0
e     NaN
f    96.0
g     NaN
dtype: float64
a    0.833333
b    1.000000
c    1.818182
d    2.142857
e         NaN
f    5.000000
g         NaN
dtype: 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']+1

test_data['marital'],jnum=pd.factorize(test_data['marital'])
test_data['marital']=test_data['marital']+1

test_data['education'],jnum=pd.factorize(test_data['education'])
test_data['education']=test_data['education']+1

test_data['default'],jnum=pd.factorize(test_data['default'])
test_data['default']=test_data['default']+1

test_data['housing'],jnum=pd.factorize(test_data['housing'])
test_data['housing']=test_data['housing']+1

test_data['loan'],jnum=pd.factorize(test_data['loan'])
test_data['loan']=test_data['loan']+1

test_data['contact'],jnum=pd.factorize(test_data['contact'])
test_data['contact']=test_data['contact']+1

test_data['month'],jnum=pd.factorize(test_data['month'])
test_data['month']=test_data['month']+1

test_data['poutcome'],jnum=pd.factorize(test_data['poutcome'])
test_data['poutcome']=test_data['poutcome']+1

test_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和poutcome
test_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.811077
1    2.963418
2    2.295078
3    0.279647
4    6.564293
5    1.146455
6    1.903623
7    1.157710
8    2.921304
9    2.397009
dtype: 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.279647
1    1.146455
2    1.157710
3    1.903623
4    2.295078
5    2.397009
6    2.921304
7    2.963418
8    5.811077
9    6.564293
dtype: 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.000000
mean      2.743961
std       2.006956
min       0.279647
25%       1.344189
50%       2.346044
75%       2.952890
max       6.564293
dtype: 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.000000
Min           0.279647
Which_Min     3.000000
Q1            1.344189
Median        2.346044
Q3            2.952890
Mean          2.743961
Max           6.564293
Which_Max     4.000000
Mad           1.456849
Var           4.027872
Std           2.006956
Skew          1.045776
Kurt          0.393228
dtype: 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    x3
0  5.811077  0.181474  33.0
1  2.963418  0.482190  17.0
2  2.295078  0.425659  71.0
3  0.279647  0.102589  45.0
4  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           25317
unique             12
top       blue-collar
freq             5456
Name: job, dtype: object
test_data['job'].describe()  #数值型数据的描述
count    10852.000000
mean         5.593255
std          2.727318
min          1.000000
25%          3.000000
50%          6.000000
75%          8.000000
max         12.000000
Name: 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.000000
x2   -0.075466
x3   -0.393609
dtype: float64
#数值型变量间的协方差矩阵
df.cov()

OK,今天的pandas实操演示就到这里,剩下的内容我们下期见。

上期问题:

你是淘宝的数据分析师,现在需要你预估双十一的销量,你不能获得双十一当天和之前的所有数据。只能获得11月12日开始的数据,你应该如何预估?

答案解析:

因为是开放题,所以没有固定答案,大家的回答分为两类:

  • 一类是通过后续双十一的销量,判断16年,缺点是需要等一年,优点是简单到不像话。
  • 二类是通过11月12日之后的销量数据,往前预估,期间会考虑一些权重。缺点是双十一属于波峰,预估难度大,优点是可操作性好。

因为题目主要看的是分析思维,目的是找出可能的思路,所以有没有其他的方法呢?我们尝试把思维放开,因为销量能反应商品,有没有其他维度?

我们可能会想到:退换货率、和商品评价率。因为双十一的商品只能在12日后退换货和收货后评价,我们就能根据这两个指标平日的平均比率,以及双十一商品的后续退换和评价总数,预估卖出总量。退换货率肯定会虚高一些(毕竟双十一退货不少),那么商品评价率更准确。

还有其他方法么?当然有,比如会有不少人用蚂蚁花呗支付双十一,那么后续还款的比率能不能预估?

如果再将思路放开呢?虽然我不知道淘宝当天的数据,但是可以寻求外部数据,比如京东,京东的双十一销量是多少,是平时的多少倍,那么就用这个倍数去预估淘宝的。

整体的分析结构就分为:

外部数据:

  • 京东等其他平台双十一销量

内部数据

  • 商品数据-商品评价率、退换货率、商品销量
  • 支付数据-蚂蚁花呗支付比率等
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-09-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 数据分析1480 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1 数据结构的简介
    • 1.1 Series的创建 三种方法
      • 通过一维数组创建序列m
      • 通过字典的方式创建序列
      • 通过已有DataFrame创建
    • 1.2 DataFrame的创建 三种方法
      • 通过二维数组创建数据框
      • 通过字典列表的方式创建数据框
      • 通过嵌套字典的方式创建数据框
  • 2 数据索引index
    • 2.1 通过索引值或索引标签获取数据
      • 通过index属性获取序列的索引值
      • 为index重新赋值
      • 通过索引获取数据
    • 2.2 自动化对齐
      • 非数值值特征数值化
      • 查询数据的前5行
      • 查询数据的末尾5行
      • 查询指定的行
      • 查询指定的列
      • 查询指定的行和列
      • 查询年龄为51的信息
      • 查询工作为5以上的年龄在51的信息
      • 查询工作为5以上,年龄在51的人员,并且只选取指定列
      • 非空元素的计算
      • 最小值
      • 最大值
      • 最小值的位置
      • 最大值的位置
      • 10%分位数
      • 求和
      • 平均数
      • 中位数
      • 众数
      • 方差
      • 标准差
      • 平均绝对偏差
      • 偏度
      • 峰度
      • 一次性输出多个描述性统计指标
  • 3 pandas查询数据
  • 4 对DataFrames进行统计分析
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档