Pandas实践_pandas基础


一、文件的读取和写入

1.文件读取

pandas可以读取的文件格式有很多,这里主要介绍读取csv, excel, txt文件。

import numpy as np
import pandas as pd

df_csv = pd.read_csv('../data/my_csv.csv')
df_csv
#   col1	col2	col3	col4	col5
#0	2   	a   	1.4 	apple	2020/1/1
#1	3   	b   	3.4 	banana	2020/1/2



df_txt = pd.read_table('../data/my_table.txt')
df_txt
#	col1	col2	col3	col4
#0	2   	a   	1.4  	apple 2020/1/1
#1	3   	b   	3.4  	banana 2020/1/2



df_excel = pd.read_excel('../data/my_excel.xlsx')
df_excel
#	col1	col2	col3	col4	col5
#0	2   	a   	1.4 	apple	2020/1/1
#1	3   	b   	3.4 	banana	2020/1/2
pd.read_table('../data/my_table.txt', header=None)
#	0   	1   	2   	3
#0	col1	col2	col3	col4
#1	2   	a   	1.4 	apple 2020/1/1



pd.read_csv('../data/my_csv.csv', index_col=['col1', 'col2'])
#	        	col3	col4	col5
#col1	col2	    	    	
#2  	a	    1.4 	apple	2020/1/1



pd.read_table('../data/my_table.txt', usecols=['col1', 'col2'])
#  	col1	col2
#0	2   	a
#1	3   	b



pd.read_csv('../data/my_csv.csv', parse_dates=['col5'])
#	col1	col2	col3	col4	col5
#0	2   	a   	1.4  	apple	2020-01-01
#1	3   	b   	3.4 	banana	2020-01-02



pd.read_excel('../data/my_excel.xlsx', nrows=2)
#	col1	col2	col3	col4	col5
#0	2   	a   	1.4 	apple	2020/1/1
#1	3   	b   	3.4 	banana	2020/1/2

2.数据写入

一般在数据写入中,最常用的操作是把index设置为False,特别当索引没有特殊意义的时候,这样的行为能把索引在保存的时候去除。

df_csv.to_csv('../data/my_csv_saved.csv', index=False)
df_excel.to_excel('../data/my_excel_saved.xlsx', index=False)

二、基本数据结构

pandas中具有两种基本的数据存储结构,存储一维values的Series和存储二维values的DataFrame,在这两种结构上定义了很多的属性和方法。

1.Series

Series一般由四个部分组成,分别是序列的值data、索引index、存储类型dtype、序列的名字name。其中,索引也可以指定它的名字,默认为空。

s = pd.Series(data = [100, 'a', {'dic1':5}],
              index = pd.Index(['id1', 20, 'third'], name='my_idx'),
              dtype = 'object',
              name = 'my_name')
s
#my_idx
#,id1              100
#,20                 a
#,third    {'dic1': 5}
#,Name: my_name, dtype: object

对于这些属性,可以通过 . 的方式来获取:

s.values
#array([100, 'a', {'dic1': 5}], dtype=object)


s.index
#Index(['id1', 20, 'third'], dtype='object', name='my_idx')


s.dtype
#dtype('O')


s.name
#'my_name'

利用.shape可以获取序列的长度:

s.shape
# (3,)

2.DataFrame

DataFrame在Series的基础上增加了列索引,一个数据框可以由二维的data与行列索引来构造:

data = [[1, 'a', 1.2], [2, 'b', 2.2], [3, 'c', 3.2]]
df = pd.DataFrame(data = data,
                  index = ['row_%d'%i for i in range(3)],
                  columns=['col_0', 'col_1', 'col_2'])
df
#      col_0	col_1	col_2
#row_0	1   	a   	1.2
#row_1	2   	b   	2.2
#row_2	3   	c   	3.2

但一般而言,更多的时候会采用从列索引名到数据的映射来构造数据框,同时再加上行索引:

df = pd.DataFrame(data = {'col_0': [1,2,3],
                          'col_1':list('abc'),
                          'col_2': [1.2, 2.2, 3.2]},
                  index = ['row_%d'%i for i in range(3)])
df
#  	col_0	col_1	col_2
#row_0	1   	a   	1.2
#row_1	2   	b   	2.2
#row_2	3   	c   	3.2

由于这种映射关系,在DataFrame中可以用[col_name]与[col_list]来取出相应的列与由多个列组成的表,结果分别为Series和DataFrame:

df['col_0']
#row_0    1
#,row_1    2
#,row_2    3
#,Name: col_0, dtype: int64

df[['col_0', 'col_1']]
#	   col_0	col_1
#row_0	1   	a
#row_1	2   	b
#row_2	3   	c

与Series类似,在数据框中同样可以取出相应的属性:

df.values
#array([[1, 'a', 1.2],
#,       [2, 'b', 2.2],
#,       [3, 'c', 3.2]], dtype=object)

df.index
#Index(['row_0', 'row_1', 'row_2'], dtype='object')

df.columns
#Index(['col_0', 'col_1', 'col_2'], dtype='object')

df.dtypes # 返回的是值为相应列数据类型的Series
#col_0      int64
#,col_1     object
#,col_2    float64
#,dtype: object

df.shape
#(3, 3)

df.T # 通过.T可以把DataFrame进行转置:
#      row_0	row_1	row_2
#col_0	1   	2   	3
#col_1	a   	b   	c
#col_2	1.2 	2.2 	3.2

三、常用基本函数

为了进行举例说明,在接下来的部分和其余章节都将会使用一份learn_pandas.csv的虚拟数据集,它记录了四所学校学生的体测个人信息。

df = pd.read_csv('../data/learn_pandas.csv')
df.columns
# Index(['School', 'Grade', 'Name', 'Gender', 'Height', 'Weight', 'Transfer',
#,       'Test_Number', 'Test_Date', 'Time_Record'],
#,      dtype='object')

上述列名依次代表学校、年级、姓名、性别、身高、体重、是否为转系生、体测场次、测试时间、1000米成绩,只需使用其中的前七列。

df = df[df.columns[:7]]

1.汇总函数

head, tail函数分别表示返回表或者序列的前n行和后n行,其中n默认为5:

df.head(2)
#	School	Grade	Name	Gender	Height	Weight	Transfer
#0	Shanghai Jiao Tong University	Freshman	Gaopeng Yang	Female	158.9	46.0	N
#1	Peking University	Freshman	Changqiang You	Male	166.5	70.0	N


df.tail(3)
#	School	Grade	Name	Gender	Height	Weight	Transfer
#197	Shanghai Jiao Tong University	Senior	Chengqiang Chu	Female	153.9	45.0	N
#198	Shanghai Jiao Tong University	Senior	Chengmei Shen	Male	175.3	71.0	N
#199	Tsinghua University	Sophomore	Chunpeng Lv	Male	155.7	51.0	N

info, describe分别返回表的信息概况和表中数值列对应的主要统计量

df.info()
#<class 'pandas.core.frame.DataFrame'>
#RangeIndex: 200 entries, 0 to 199
#Data columns (total 7 columns):
# #   Column    Non-Null Count  Dtype  
#---  ------    --------------  -----  
# 0   School    200 non-null    object 
# 1   Grade     200 non-null    object 
# 2   Name      200 non-null    object 
# 3   Gender    200 non-null    object 
# 4   Height    183 non-null    float64
# 5   Weight    189 non-null    float64
# 6   Transfer  188 non-null    object 
#dtypes: float64(2), object(5)
#memory usage: 11.1+ KB



df.describe()
#   	Height  	Weight
#count	183.000000	189.000000
#mean	163.218033	55.015873
#std	8.608879	12.824294
#min	145.400000	34.000000
#25%	157.150000	46.000000
#50%	161.900000	51.000000
#75%	167.500000	65.000000
#max	193.900000	89.000000

2.特征统计函数

在Series和DataFrame上定义了许多统计函数,最常见的是sum, mean, median, var, std, max, min。例如,选出身高和体重列进行演示:

df_demo = df[['Height', 'Weight']]
df_demo.mean()
#Height    163.218033
#,Weight     55.015873
#,dtype: float64



df_demo.max()
#Height    193.9
#,Weight     89.0
#,dtype: float64

此外,需要介绍的是quantile, count, idxmax这三个函数,它们分别返回的是分位数、非缺失值个数、最大值对应的索引:

df_demo.quantile(0.75)
#Height    167.5
#,Weight     65.0
#,Name: 0.75, dtype: float64


df_demo.count()
#Height    183
#,Weight    189
#,dtype: int64


df_demo.idxmax() # idxmin是对应的函数
#Height    193
#,Weight      2
#,dtype: int64

上面这些所有的函数,由于操作后返回的是标量,所以又称为聚合函数,它们有一个公共参数axis,默认为0代表逐列聚合,如果设置为1则表示逐行聚合:

df_demo.mean(axis=1).head() # 在这个数据集上体重和身高的均值并没有意义
#0    102.45
#,1    118.25
#,2    138.95
#,3     41.00
#,4    124.00
#,dtype: float64

3.唯一值函数

对序列使用unique和nunique可以分别得到其唯一值组成的列表和唯一值的个数:

df['School'].unique()
#array(['Shanghai Jiao Tong University', 'Peking University',
#,       'Fudan University', 'Tsinghua University'], dtype=object)



df['School'].nunique()
#Tsinghua University              69
#,Shanghai Jiao Tong University    57
#,Fudan University                 40
#,Peking University                34
#,Name: School, dtype: int64

如果想要观察多个列组合的唯一值,可以使用drop_duplicates。其中的关键参数是keep,默认值first表示每个组合保留第一次出现的所在行,last表示保留最后一次出现的所在行,False表示把所有重复组合所在的行剔除。

df_demo = df[['Gender','Transfer','Name']]
df_demo.drop_duplicates(['Gender', 'Transfer'])
#	Gender	Transfer	Name
#0	Female	N       	Gaopeng Yang
#1	Male	N       	Changqiang You
#12	Female	NaN     	Peng You
#21	Male	NaN     	Xiaopeng Shen
#36	Male	Y       	Xiaojuan Qin
#43	Female	Y       	Gaoli Feng



df_demo.drop_duplicates(['Gender', 'Transfer'], keep='last')
#   	Gender	Transfer	Name
#147	Male	NaN     	Juan You
#150	Male	Y       	Chengpeng You
#169	Female	Y       	Chengquan Qin
#194	Female	NaN     	Yanmei Qian
#197	Female	N       	Chengqiang Chu
#199	Male	N       	Chunpeng Lv



df_demo.drop_duplicates(['Name', 'Gender'], keep=False).head() # 保留只出现过一次的性别和姓名组合
#	Gender	Transfer	Name
#0	Female	N       	Gaopeng Yang
#1	Male	N       	Changqiang You
#2	Male	N       	Mei Sun
#4	Male	N       	Gaojuan You
#5	Female	N       	Xiaoli Qian



df['School'].drop_duplicates() # 在Series上也可以使用
#0    Shanghai Jiao Tong University
#,1                Peking University
#,3                 Fudan University
#,5              Tsinghua University
#,Name: School, dtype: object

此外,duplicated和drop_duplicates的功能类似,但前者返回了是否为唯一值的布尔列表,其keep参数与后者一致。其返回的序列,把重复元素设为True,否则为False。 drop_duplicates等价于把duplicated为True的对应行剔除。

df_demo.duplicated(['Gender', 'Transfer']).head()
#0    False
#,1    False
#,2     True
#,3     True
#,4     True
#,dtype: bool



df['School'].duplicated().head() # 在Series上也可以使用
#0    False
#,1    False
#,2     True
#,3    False
#,4     True
#,Name: School, dtype: bool

4.替换函数

一般而言,替换操作是针对某一个列进行的,因此下面的例子都以Series举例。pandas中的替换函数可以归纳为三类:映射替换、逻辑替换、数值替换。其中映射替换包含replace方法、str.replace方法以及cat.codes方法,此处介绍replace的用法。

在replace中,可以通过字典构造,或者传入两个列表来进行替换:

df['Gender'].replace({'Female':0, 'Male':1}).head()
#0    0
#,1    1
#,2    1
#,3    0
#,4    1
#,Name: Gender, dtype: int64


df['Gender'].replace(['Female', 'Male'], [0, 1]).head()
#0    0
#,1    1
#,2    1
#,3    0
#,4    1
#,Name: Gender, dtype: int64

另外,replace还有一种特殊的方向替换,指定method参数为ffill则为用前面一个最近的未被替换的值进行替换,bfill则使用后面最近的未被替换的值进行替换。从下面的例子可以看到,它们的结果是不同的:

s = pd.Series(['a', 1, 'b', 2, 1, 1, 'a'])
s.replace([1, 2], method='ffill')
#0    a
#,1    a
#,2    b
#,3    b
#,4    b
#,5    b
#,6    a
#,dtype: object



s.replace([1, 2], method='bfill')
#0    a
#,1    b
#,2    b
#,3    a
#,4    a
#,5    a
#,6    a
#,dtype: object

逻辑替换包括了where和mask,这两个函数是完全对称的:where函数在传入条件为False的对应行进行替换,而mask在传入条件为True的对应行进行替换,当不指定替换值时,替换为缺失值。

s = pd.Series([-1, 1.2345, 100, -50])
s.where(s<0)
#0    -1.0
#,1     NaN
#,2     NaN
#,3   -50.0
#,dtype: float64


s.where(s<0, 100)
#0     -1.0
#,1    100.0
#,2    100.0
#,3    -50.0
#,dtype: float64


s.mask(s<0)
#0         NaN
#,1      1.2345
#,2    100.0000
#,3         NaN
#,dtype: float64


s.mask(s<0, -50)
#0    -50.0000
#,1      1.2345
#,2    100.0000
#,3    -50.0000
#,dtype: float64

需要注意的是,传入的条件只需是与被调用的Series索引一致的布尔序列即可:

s_condition= pd.Series([True,False,False,True],index=s.index)
s.mask(s_condition, -50)
#0    -50.0000
#,1      1.2345
#,2    100.0000
#,3    -50.0000
#,dtype: float64

数值替换包含了round, abs, clip方法,它们分别表示按照给定精度四舍五入、取绝对值和截断:

s = pd.Series([-1, 1.2345, 100, -50])
s.round(2)
#0     -1.00
#,1      1.23
#,2    100.00
#,3    -50.00
#,dtype: float64


s.abs()
#0      1.0000
#,1      1.2345
#,2    100.0000
#,3     50.0000
#,dtype: float64


s.clip(0, 2) # 前两个数分别表示上下截断边界
#0    0.0000
#,1    1.2345
#,2    2.0000
#,3    0.0000
#,dtype: float64

5.排序函数

排序共有两种方式,其一为值排序,其二为索引排序,对应的函数是sort_values和sort_index。

为了演示排序函数,下面先利用set_index方法把年级和姓名两列作为索引

df_demo = df[['Grade', 'Name', 'Height', 'Weight']].set_index(['Grade','Name'])
df_demo.head(3)
#                         Height	Weight
Grade	    Name		
Freshman	Gaopeng Yang	158.9	46.0
            Changqiang You	166.5	70.0
Senior   	Mei Sun     	188.9	89.0

对身高进行排序,默认参数ascending=True为升序:

df_demo.sort_values('Height').head()
#                   		Height	Weight
#Grade  	Name		
#Junior 	Xiaoli Chu  	145.4	34.0
#Senior 	Gaomei Lv   	147.3	34.0
#Sophomore	Peng Han    	147.8	34.0
#Senior 	Changli Lv  	148.7	41.0
#Sophomore	Changjuan You	150.5	40.0



df_demo.sort_values('Height', ascending=False).head()
#                   		Height	Weight
#Grade  	Name		
#Senior 	Xiaoqiang Qin	193.9	79.0
#           Mei Sun     	188.9	89.0
#           Gaoli Zhao  	186.5	83.0
#Freshman	Qiang Han   	185.3	87.0
#Senior 	Qiang Zheng 	183.9	87.0

在排序中,经常遇到多列排序的问题,比如在体重相同的情况下,对身高进行排序,并且保持身高降序排列,体重升序排列:

df_demo.sort_values(['Weight','Height'],ascending=[True,False]).head()
#                   		Height	Weight
#Grade  	Name		
#Sophomore	Peng Han    	147.8	34.0
#Senior 	Gaomei Lv   	147.3	34.0
#Junior 	Xiaoli Chu  	145.4	34.0
#Sophomore	Qiang Zhou  	150.5	36.0
#Freshman	Yanqiang Xu 	152.4	38.0

索引排序的用法和值排序完全一致,只不过元素的值在索引中,此时需要指定索引层的名字或者层号,用参数level表示。另外,需要注意的是字符串的排列顺序由字母顺序决定。

df_demo.sort_index(level=['Grade','Name'],ascending=[True,False]).head()
#                   		Height	Weight
#Grade    	Name		
#Freshman	Yanquan Wang	163.5	55.0
#           Yanqiang Xu 	152.4	38.0
#           Yanqiang Feng	162.3	51.0
#           Yanpeng Lv  	NaN 	65.0
#           Yanli Zhang 	165.1	52.0

6.apply方法

apply方法常用于DataFrame的行迭代或者列迭代,它的axis含义与第2小节中的统计聚合函数一致,apply的参数往往是一个以序列为输入的函数。例如对于.mean(),使用apply可以如下地写出:

df_demo = df[['Height', 'Weight']]
def my_mean(x):
     res = x.mean()
    return res
df_demo.apply(my_mean)
#Height    163.218033
#,Weight     55.015873
#,dtype: float64

同样的,可以利用lambda表达式使得书写简洁,这里的x就指代被调用的df_demo表中逐个输入的序列:

df_demo.apply(lambda x:x.mean())
#Height    163.218033
#,Weight     55.015873
#,dtype: float64

若指定axis=1,那么每次传入函数的就是行元素组成的Series,其结果与之前的逐行均值结果一致。

df_demo.apply(lambda x:x.mean(), axis=1).head()
#0    102.45
#,1    118.25
#,2    138.95
#,3     41.00
#,4    124.00
#,dtype: float64

这里再举一个例子:mad函数返回的是一个序列中偏离该序列均值的绝对值大小的均值,例如序列1,3,7,10中,均值为5.25,每一个元素偏离的绝对值为4.25,2.25,1.75,4.75,这个偏离序列的均值为3.25。现在利用apply计算升高和体重的mad指标:

df_demo.apply(lambda x:(x-x.mean()).abs().mean())
#Height     6.707229
#,Weight    10.391870
#,dtype: float64

这与使用内置的mad函数计算结果一致:

df_demo.mad()
#Height     6.707229
#,Weight    10.391870
#,dtype: float64

四、窗口对象

pandas中有3类窗口,分别是滑动窗口rolling、扩张窗口expanding以及指数加权窗口ewm。需要说明的是,以日期偏置为窗口大小的滑动窗口将在第十章讨论,指数加权窗口见本章练习。

1.滑窗对象

要使用滑窗函数,就必须先要对一个序列使用.rolling得到滑窗对象,其最重要的参数为窗口大小window。

s = pd.Series([1,2,3,4,5])
roller = s.rolling(window = 3)
roller

在得到了滑窗对象后,能够使用相应的聚合函数进行计算,需要注意的是窗口包含当前行所在的元素,例如在第四个位置进行均值运算时,应当计算(2+3+4)/3,而不是(1+2+3)/3:

roller.mean()
#0    NaN
#,1    NaN
#,2    2.0
#,3    3.0
#,4    4.0
#,dtype: float64


roller.sum()
#0     NaN
#,1     NaN
#,2     6.0
#,3     9.0
#,4    12.0
#,dtype: float64

对于滑动相关系数或滑动协方差的计算,可以如下写出:

s2 = pd.Series([1,2,6,16,30])
roller.cov(s2)
#0     NaN
#,1     NaN
#,2     2.5
#,3     7.0
#,4    12.0
#,dtype: float64


roller.corr(s2)
#0         NaN
#,1         NaN
#,2    0.944911
#,3    0.970725
#,4    0.995402
#,dtype: float64

此外,还支持使用apply传入自定义函数,其传入值是对应窗口的Series,例如上述的均值函数可以等效表示:

roller.apply(lambda x:x.mean())
#0    NaN
#,1    NaN
#,2    2.0
#,3    3.0
#,4    4.0
#,dtype: float64

shift, diff, pct_change是一组类滑窗函数,它们的公共参数为periods=n,默认为1,分别表示取向前第n个元素的值、与向前第n个元素做差(与Numpy中不同,后者表示n阶差分)、与向前第n个元素相比计算增长率。这里的n可以为负,表示反方向的类似操作。

s = pd.Series([1,3,6,10,15])
s.shift(2)
#0    NaN
#,1    NaN
#,2    1.0
#,3    3.0
#,4    6.0
#,dtype: float64


s.diff(3)
#0     NaN
#,1     NaN
#,2     NaN
#,3     9.0
#,4    12.0
#,dtype: float64


s.pct_change()
#0         NaN
#,1    2.000000
#,2    1.000000
#,3    0.666667
#,4    0.500000
#,dtype: float64


s.shift(-1)
#0     3.0
#,1     6.0
#,2    10.0
#,3    15.0
#,4     NaN
#,dtype: float64


s.diff(-2)
#0   -5.0
#,1   -7.0
#,2   -9.0
#,3    NaN
#,4    NaN
#,dtype: float64

将其视作类滑窗函数的原因是,它们的功能可以用窗口大小为n+1的rolling方法等价代替:

s.rolling(3).apply(lambda x:list(x)[0]) # s.shift(2)
#0    NaN
#,1    NaN
#,2    1.0
#,3    3.0
#,4    6.0
#,dtype: float64


s.rolling(4).apply(lambda x:list(x)[-1]-list(x)[0]) # s.diff(3)
#0     NaN
#,1     NaN
#,2     NaN
#,3     9.0
#,4    12.0
#,dtype: float64


def my_pct(x):
     L = list(x)
    return L[-1]/L[0]-1
s.rolling(2).apply(my_pct) # s.pct_change()
#0         NaN
#,1    2.000000
#,2    1.000000
#,3    0.666667
#,4    0.500000
#,dtype: float64

2.扩张窗口

扩张窗口又称累计窗口,可以理解为一个动态长度的窗口,其窗口的大小就是从序列开始处到具体操作的对应位置,其使用的聚合函数会作用于这些逐步扩张的窗口上。具体地说,设序列为a1, a2, a3, a4,则其每个位置对应的窗口即[a1]、[a1, a2]、[a1, a2, a3]、[a1, a2, a3, a4]。

s = pd.Series([1, 3, 6, 10])
s.expanding().mean()
#0    1.000000
#,1    2.000000
#,2    3.333333
#,3    5.000000
#,dtype: float64

参考:阿里云天池

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值