五、Pandas初步使用

python编程快速上手(持续更新中…)


5.1 Pandas介绍

1 Pandas介绍

  • 2008年WesMcKinney开发出的库
  • 专门用于数据挖掘的开源python库
  • 以Numpy为基础,借力Numpy模块在计算方面性能高的优势
  • 基于matplotlib,能够简便的画图
  • 独特的数据结构

2 为什么使用Pandas

Numpy已经能够帮助我们处理数据,能够结合matplotlib解决部分数据展示等问题,那么pandas学习的目的在什么地方呢?

增强图表可读性

回忆我们在numpy当中创建学生成绩表样式:
返回结果:

array([[92, 55, 78, 50, 50],
[71, 76, 50, 48, 96],
[45, 84, 78, 51, 68],
[81, 91, 56, 54, 76],
[86, 66, 77, 67, 95],
[46, 86, 56, 61, 99],
[46, 95, 44, 46, 56],
[80, 50, 45, 65, 57],
[41, 93, 90, 41, 97],
[65, 83, 57, 57, 40]])

如果数据展示为这样,可读性就会更友好:

在这里插入图片描述
便捷的数据处理能力
在这里插入图片描述
读取文件方便
封装了Matplotlib、Numpy的画图和计算

5.2 Pandas数据结构

Pandas中一共有三种数据结构,分别为:Series、DataFrame和MultiIndex(老版本中叫Panel )。
其中Series是一维数据结构,DataFrame是二维的表格型数据结构,MultiIndex是三维的数据结构。

1.Series

Series是一个类似于一维数组的数据结构,它能够保存任何类型的数据,比如整数、字符串、浮点数等,主要由一组数据和与之相关的索引两部分构成。

1.1 Series的创建
# 导入pandasimport pandas as pd

pd.Series(data=None, index=None, dtype=None)

参数:

  • data:传入的数据,可以是ndarray、list等
  • index:索引,必须是唯一的,且与数据的长度相等。如果没有传入索引参数,则默认会自动创建一个从0-N的整数索引。
  • dtype:数据的类型

通过已有数据创建

指定内容,默认索引

pd.Series(np.arange(10))

指定索引

pd.Series([6.7,5.6,3,10,2], index=[1,2,3,4,5])

#运行结果
1 6.7
2 5.6
3 3.0
4 10.0
5 2.0
dtype: float64

通过字典数据创建

color_count = pd.Series({‘red’:100, ‘blue’:200, ‘green’: 500, ‘yellow’:1000})
color_count

#运行结果
blue 200
green 500
red 100
yellow 1000
dtype: int64

1.2 Series的属性

为了更方便地操作Series对象中的索引和数据,Series中提供了两个属性index和values
index

color_count.index

#结果
Index([‘blue’, ‘green’, ‘red’, ‘yellow’], dtype=‘object’)

values

color_count.values

#结果
array([ 200, 500, 100, 1000])

也可以使用索引来获取数据:

color_count[2]

#结果100

2.DataFrame

DataFrame是一个类似于二维数组或表格(如excel)的对象,既有行索引,又有列索引

  • 行索引,表明不同行,横向索引,叫index,0轴,axis=0
  • 列索引,表名不同列,纵向索引,叫columns,1轴,axis=1
    在这里插入图片描述
2.1 DataFrame的创建

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2.2 DataFrame的属性

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2.3 DatatFrame索引的设置

2.3.1 修改行列索引值
在这里插入图片描述
在这里插入图片描述
2.3.2 重设索引
reset_index(drop=False)

  • 设置新的下标索引
  • drop:默认为False,不删除原来索引,如果为True,删除原来的索引值

#重置索引,drop=False
data.reset_index()

2.3.3 以某列值设置为新的索引
set_index(keys, drop=True)

  • keys : 列索引名成或者列索引名称的列表
  • drop : boolean, default True.当做新的索引,删除原来的列

#重置索引,drop=False
data.reset_index()

#重置索引,drop=True
data.reset_index(drop=True)

在这里插入图片描述
在这里插入图片描述
:通过刚才的设置,这样DataFrame就变成了一个具有MultiIndex的DataFrame

3.MultiIndex与Panel

3.1 MultiIndex

MultiIndex是三维的数据结构;
多级索引(也称层次化索引)是pandas的重要功能,可以在Series、DataFrame对象上拥有2个以及2个以上的索引。
3.1.1 multiIndex的特性
打印刚才的df的行索引结果
在这里插入图片描述
多级或分层索引对象。
index属性

  • names:levels的名称
  • levels:每个level的元组值

df.index.names# FrozenList([‘year’, ‘month’])

df.index.levels# FrozenList([[1, 2], [1, 4, 7, 10]])

3.1.2 multiIndex的创建

arrays = [[1, 1, 2, 2], [‘red’, ‘blue’, ‘red’, ‘blue’]]
pd.MultiIndex.from_arrays(arrays, names=(‘number’, ‘color’))
#结果
MultiIndex(levels=[[1, 2], [‘blue’, ‘red’]],
codes=[[0, 0, 1, 1], [1, 0, 1, 0]],
names=[‘number’, ‘color’])

3.2 Panel(已弃用)

3.2.1 panel的创建

class pandas.Panel(data=None, items=None, major_axis=None, minor_axis=None)

**作用:**存储3维数组的Panel结构

参数:

data : ndarray或者dataframe

items : 索引或类似数组的对象,axis=0

major_axis : 索引或类似数组的对象,axis=1

minor_axis : 索引或类似数组的对象,axis=2

p = pd.Panel(data=np.arange(24).reshape(4,3,2),
                 items=list('ABCD'),
                 major_axis=pd.date_range('20130101', periods=3),
                 minor_axis=['first', 'second'])

# 结果
<class 'pandas.core.panel.Panel'>
Dimensions: 4 (items) x 3 (major_axis) x 2 (minor_axis)
Items axis: A to D
Major_axis axis: 2013-01-01 00:00:00 to 2013-01-03 00:00:00
Minor_axis axis: first to second

3.2.2 查看panel数据
p[:,:,“first”]
p[“B”,:,:]

注:Pandas从版本0.20.0开始弃用:推荐的用于表示3D数据的方法是通过DataFrame上的MultiIndex方法

5.3 基本数据操作

# 读取文件
data = pd.read_csv("./data/stock_day.csv")
# 删除一些列,让数据更简单些,再去做后面的操作
data = data.drop(["ma5","ma10","ma20","v_ma5","v_ma10","v_ma20"], axis=1)

1 索引操作

Numpy当中我们已经讲过使用索引选取序列和切片选择,pandas也支持类似的操作,也可以直接使用列名、行名称,甚至组合使用。

1.1 直接使用行列索引(先列后行)

获取’2018-02-27’这天的’close’的结果

# 直接使用行列索引名字的方式(先列后行)
data['open']['2018-02-27']23.53

# 不支持的操作# 错误
data['2018-02-27']['open']# 错误
data[:1, :2]
1.2 结合loc或者iloc使用索引

获取从’2018-02-27’:‘2018-02-22’,'open’的结果

# 使用loc:只能指定行列索引的名字
data.loc['2018-02-27':'2018-02-22', 'open']
2018-02-27    23.532018-02-26    22.802018-02-23    22.88
Name: open, dtype: float64

# 使用iloc可以通过索引的下标去获取# 获取前3天数据,5列的结果
data.iloc[:3, :5]

            open    high    close    low2018-02-27    23.53    25.88    24.16    23.532018-02-26    22.80    23.78    23.53    22.802018-02-23    22.88    23.37    22.82    22.71

1.3 使用ix组合索引(已弃用)

Warning:Starting in 0.20.0, the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.
获取行第1天到第4天,[‘open’, ‘close’, ‘high’, ‘low’]这个四个指标的结果

# 使用ix进行下表和名称组合做引
data.ix[0:4, ['open', 'close', 'high', 'low']]

# 推荐使用loc和iloc来获取的方式
data.loc[data.index[0:4], ['open', 'close', 'high', 'low']]
data.iloc[0:4, data.columns.get_indexer(['open', 'close', 'high', 'low'])]

            open    close    high    low2018-02-27    23.53    24.16    25.88    23.532018-02-26    22.80    23.53    23.78    22.802018-02-23    22.88    22.82    23.37    22.712018-02-22    22.25    22.28    22.76    22.02

2 赋值操作

对DataFrame当中的close列进行重新赋值为1

# 直接修改原来的值
data['close'] = 1# 或者
data.close = 1

3 排序

排序有两种形式,一种对于索引进行排序,一种对于内容进行排序

3.1 DataFrame排序

使用df.sort_values(by=, ascending=)

  • 单个键或者多个键进行排序,
  • 参数:

by:指定排序参考的键

  • ascending:默认升序
  • ascending=False:降序
  • ascending=True:升序
# 按照开盘价大小进行排序 , 使用ascending指定按照大小排序
data.sort_values(by="open", ascending=True).head()

在这里插入图片描述

# 按照多个键进行排序
data.sort_values(by=['open', 'high'])

在这里插入图片描述
使用df.sort_index给索引进行排序
这个股票的日期索引原来是从大到小,现在重新排序,从小到大

# 对索引进行排序
data.sort_index()

在这里插入图片描述

3.2 Series排序

使用series.sort_values(ascending=True)进行排序
series排序时,只有一列,不需要参数

data['p_change'].sort_values(ascending=True).head()
2015-09-01   -10.032015-09-14   -10.022016-01-11   -10.022015-07-15   -10.022015-08-26   -10.01
Name: p_change, dtype: float64

使用series.sort_index()进行排序
与df一致

# 对索引进行排序
data['p_change'].sort_index().head()
2015-03-02    2.622015-03-03    1.442015-03-04    1.572015-03-05    2.022015-03-06    8.51
Name: p_change, dtype: float64

5.4 DataFrame运算

1 算术运算

add(other)
比如进行数学运算加上具体的一个数字

data[‘open’].add(1)
2018-02-27 24.532018-02-26 23.802018-02-23 23.882018-02-22 23.252018-02-14 22.49

sub(other)'

2 逻辑运算

2.1 逻辑运算符号

例如筛选data[“open”] > 23的日期数据

  • data[“open”] > 23返回逻辑结果

data[“open”] > 23
2018-02-27 True2018-02-26 False2018-02-23 False2018-02-22 False2018-02-14 False

# 逻辑判断的结果可以作为筛选的依据
data[data["open"] > 23].head()

在这里插入图片描述
完成多个逻辑判断,

data[(data[“open”] > 23) & (data[“open”] < 24)].head()
在这里插入图片描述

2.2 逻辑运算函数

query(expr)

  • oexpr:查询字符串

通过query使得刚才的过程更加方便简单

data.query(“open<24 & open>23”).head()

-isin(values)
例如判断’open’是否为23.53和23.85

# 可以指定值进行一个判断,从而进行筛选操作
data[data["open"].isin([23.53, 23.85])]

在这里插入图片描述

3 统计运算

3.1 describe

综合分析: 能够直接得出很多统计结果,count, mean, std, min, max 等

# 计算平均值、标准差、最大值、最小值
data.describe()

3.2 统计函数

Numpy当中已经详细介绍,在这里我们演示min(最小值), max(最大值), mean(平均值), median(中位数), var(方差), std(标准差),mode(众数)结果:
在这里插入图片描述
对于单个函数去进行统计的时候,坐标轴还是按照默认列“columns” (axis=0, default),如果要对行“index” 需要指定(axis=1)

max()、min()

# 使用统计函数:0 代表列求结果, 1 代表行求统计结果
data.max(0)

open                   34.99
high                   36.35
close                  35.21
low                    34.01
volume             501915.41
price_change            3.03
p_change               10.03
turnover               12.56
my_price_change         3.41
dtype: float64

std()、var()

# 方差
data.var(0)

open               1.545255e+01
high               1.662665e+01
close              1.554572e+01
low                1.437902e+01
volume             5.458124e+09
price_change       8.072595e-01
p_change           1.664394e+01
turnover           4.323800e+00
my_price_change    6.409037e-01
dtype: float64
# 标准差
data.std(0)

open                   3.930973
high                   4.077578
close                  3.942806
low                    3.791968
volume             73879.119354
price_change           0.898476
p_change               4.079698
turnover               2.079375
my_price_change        0.800565
dtype: float64

median():中位数
中位数为将数据从小到大排列,在最中间的那个数为中位数。如果没有中间数,取中间两个数的平均值

df = pd.DataFrame({'COL1' : [2,3,4,5,4,2],
                   'COL2' : [0,1,2,3,4,2]})

df.median()

COL1    3.5
COL2    2.0
dtype: float64

idxmax()、idxmin()

# 求出最大值的位置
data.idxmax(axis=0)

open               2015-06-15
high               2015-06-10
close              2015-06-12
low                2015-06-12
volume             2017-10-26
price_change       2015-06-09
p_change           2015-08-28
turnover           2017-10-26
my_price_change    2015-07-10
dtype: object

# 求出最小值的位置
data.idxmin(axis=0)

open               2015-03-02
high               2015-03-02
close              2015-09-02
low                2015-03-02
volume             2016-07-06
price_change       2015-06-15
p_change           2015-09-01
turnover           2016-07-06
my_price_change    2015-06-15
dtype: object
3.3 累计统计函数

在这里插入图片描述
那么这些累计统计函数怎么用?
以上这些函数可以对series和dataframe操作
这里我们按照时间的从前往后来进行累计

  • 排序
# 排序之后,进行累计求和
data = data.sort_index()

对p_change进行求和

stock_rise = data['p_change']# plot方法集成了前面直方图、条形图、饼图、折线图
stock_rise.cumsum()
2015-03-02      2.622015-03-03      4.062015-03-04      5.632015-03-05      7.652015-03-06     16.162015-03-09     16.372015-03-10     18.752015-03-11     16.362015-03-12     15.032015-03-13     17.582015-03-16     20.342015-03-17     22.422015-03-18     23.282015-03-19     23.742015-03-20     23.482015-03-23     23.74

那么如何让这个连续求和的结果更好的显示呢?

如果要使用plot函数,需要导入matplotlib.

import matplotlib.pyplot as plt# plot显示图形
stock_rise.cumsum().plot()# 需要调用show,才能显示出结果
plt.show()

4 自定义运算

apply(func, axis=0)

  • func:自定义函数
  • axis=0:默认是列,axis=1为行进行运算
    定义一个对列,最大值-最小值的函数

data[[‘open’, ‘close’]].apply(lambda x: x.max() - x.min(), axis=0)

open 22.74
close 22.85
dtype: float64

5.5 Pandas画图

1 pandas.DataFrame.plot

DataFrame.plot(kind=‘line’)
kind : str,需要绘制图形的种类
‘line’ : line plot (default)
‘bar’ : vertical bar plot
‘barh’ : horizontal bar plot
关于“barh”的解释:
http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.plot.barh.html
‘hist’ : histogram
‘pie’ : pie plot
‘scatter’ : scatter plot
更多细节:https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html?highlight=plot#pandas.DataFrame.plot

2 pandas.Series.plot

更多细节:https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.plot.html?highlight=plot#pandas.Series.plot

5.6 文件读取与存储

我们的数据大部分存在于文件当中,所以pandas会支持复杂的IO操作,pandas的API支持众多的文件格式,如CSV、SQL、XLS、JSON、HDF5。
:最常用的HDF5和CSV文件

1 个 CSV 文件

1.1 read_csv

pandas.read_csv(filepath_or_buffer, sep =’,’, usecols )

  • ofilepath_or_buffer:文件路径
  • sep :分隔符,默认用","隔开
  • usecols:指定读取的列名,列表形式

举例:读取之前的股票的数据

# 读取文件,并且指定只获取'open', 'close'指标
data = pd.read_csv("./data/stock_day.csv", usecols=['open', 'close'])

            open    close2018-02-27    23.53    24.162018-02-26    22.80    23.532018-02-23    22.88    22.822018-02-22    22.25    22.282018-02-14    21.49    21.92
1.2 to_csv

DataFrame.to_csv(path_or_buf=无,sep=’, ', columns=None, header=True, index=True, mode=‘w’, encoding=None)

  • path_or_buf :文件路径
  • sep :分隔符,默认用","隔开
  • columns :选择需要的列索引
  • header :boolean or list of string, default True,是否写进列索引值
  • index:是否写进行索引
  • mode:‘w’:重写, ‘a’ 追加

举例:保存读取出来的股票数据

  • 保存’open’列的数据,然后读取查看结果
# 选取10行数据保存,便于观察数据
data[:10].to_csv("./data/test.csv", columns=['open'])
# 读取,查看结果
pd.read_csv("./data/test.csv")

     Unnamed: 0    open0    2018-02-27    23.531    2018-02-26    22.802    2018-02-23    22.883    2018-02-22    22.254    2018-02-14    21.495    2018-02-13    21.406    2018-02-12    20.707    2018-02-09    21.208    2018-02-08    21.799    2018-02-07    22.69

会发现将索引存入到文件当中,变成单独的一列数据。如果需要删除,可以指定index参数,删除原来的文件,重新保存一次。

# index:存储不会讲索引值变成一列数据
data[:10].to_csv("./data/test.csv", columns=['open'], index=False)

2 HDF5

需要安装安装tables模块避免不能读取HDF5文件

pip install tables

2.1 read_hdf与to_hdf

HDF5文件的读取和存储需要指定一个键,值为要存储的DataFrame

pandas.read_hdf(path_or_buf,key =None,** kwargs)

从h5文件当中读取数据

  • path_or_buffer:文件路径
  • key:读取的键
  • 返回:这些选定对象

DataFrame.to_hdf(path_or_buf, key, \kwargs

2.2 案例

读取文件

day_close = pd.read_hdf("./data/day_close.h5")

如果读取的时候出现以下错误

存储文件

day_close.to_hdf("./data/test.h5", key=“day_close”)

再次读取的时候, 需要指定键的名字

new_close = pd.read_hdf("./data/test.h5", key=“day_close”)

注意:优先选择使用HDF5文件存储
HDF5在存储的时候支持压缩,使用的方式是blosc,这个是速度最快的也是pandas默认支持的
使用压缩可以提磁盘利用率,节省空间
HDF5还是跨平台的,可以轻松迁移到hadoop 上面

3 JSON

JSON是我们常用的一种数据交换格式,前面在前后端的交互经常用到,也会在存储的时候选择这种格式。所以我们需要知道Pandas如何进行读取和存储JSON格式。

3.1 read_json

pandas.read_json(path_or_buf=无,定向=无,典型值=‘frame’,行=False)

将JSON格式准换成默认的Pandas DataFrame格式

  • rient:字符串,指示预期的JSON字符串格式。
  • ‘split’ : 像 {index -> [index], columns -> [columns], data -> [values]}
  • split 将索引总结到索引,列名到列名,数据到数据。将三部分都分开了
  • ‘记录’ :列表如 [{列 -> 值}, … , {列 -> 值}]

记录 以的形式输出columns:values

  • ‘index’ : dict like {index -> {column -> value}}
  • index 以的形式输出index:{columns:values}…
  • ‘columns’ : dict like {column -> {index -> value}},默认该格式
  • colums 以的形式输出columns:{index:values}
    ‘值’ :只有值数组
    值 直接输出值
  • 行:布尔值,默认 False

按照每行读取json对象

  • typ : default ‘frame’, 指定转换成的对象类型系列或者dataframe
3.2 read_json 案例

数据介绍

这里使用一个新闻标题讽刺数据集,格式为json。:1讽刺的,否则为0;:新闻报道的标题;:链接到原始新闻文章。存储格式为:

{“article_link”: “https://www.huffingtonpost.com/entry/versace-black-code_us_5861fbefe4b0de3a08f600d5”, “headline”: “former versace store clerk sues over secret ‘black code’ for minority shoppers”, “is_sarcastic”: 0}
{“article_link”: “https://www.huffingtonpost.com/entry/roseanne-revival-review_us_5ab3a497e4b054d118e04365”, “headline”: “the ‘roseanne’ revival catches up to our thorny political mood, for better and worse”, “is_sarcastic”: 0}

读取

  • rient指定存储的json格式,lines指定按照行去变成一个样本

json_read = pd.read_json("./data/Sarcasm_Headlines_Dataset.json", orient=“records”, lines=True)
结果为:
在这里插入图片描述

3.3 to_json

DataFrame.to_json(path_or_buf=None, orient=None, lines=False)

-将Pandas 对象存储为json格式

  • path_or_buf=None:文件地址
  • orient:存储的json形式,{‘split’,’records’,’index’,’columns’,’values’}
  • lines:一个对象存储为一行
3.4 案例

存储文件

json_read.to_json("./data/test.json", orient=‘records’)

结果
在这里插入图片描述

4.小结

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值