一、Pandas介绍

安装:pip install pandas
官网:https://pandas.pydata.org/

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的画图和计算

3. 小结

  • pandas的优势【了解】
    • 增强图表可读性
    • 便捷的数据处理能力
    • 读取文件方便
    • 封装了Matplotlib、Numpy的画图和计算

二、Pandas数据结构

Pandas中一共有三种数据结构,分别为:Series、DataFrame和MultiIndex(老版本中叫Panel )。

其中Series是一维数据结构,DataFrame是二维的表格型数据结构,MultiIndex是三维的数据结构。

1.Series

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

在这里插入图片描述

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

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

通过已有数据创建

  • 指定内容,默认索引
pd.Series(np.arange(10))
# 运行结果
0    0
1    1
2    2
3    3
4    4
5    5
6    6
7    7
8    8
9    9
dtype: int64
  • 指定索引
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的创建
# 导入pandas
import pandas as pd

pd.DataFrame(data=None, index=None, columns=None)
  • 参数:

    • index:行标签。如果没有传入索引参数,则默认会自动创建一个从0-N的整数索引。
    • columns:列标签。如果没有传入索引参数,则默认会自动创建一个从0-N的整数索引。
  • 通过已有数据创建

举例一:

pd.DataFrame(np.random.randn(2,3))

在这里插入图片描述

回忆咱们在前面直接使用np创建的数组显示方式,比较两者的区别。

举例二:创建学生成绩表

# 生成10名同学,5门功课的数据
score = np.random.randint(40, 100, (10, 5))

# 结果
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]])

但是这样的数据形式很难看到存储的是什么的样的数据,可读性比较差!!

问题:如何让数据更有意义的显示

# 使用Pandas中的数据结构
score_df = pd.DataFrame(score)

在这里插入图片描述

给分数数据增加行列索引,显示效果更佳

效果:

在这里插入图片描述

  • 增加行、列索引
# 构造行索引序列
subjects = ["语文", "数学", "英语", "政治", "体育"]

# 构造列索引序列
stu = ['同学' + str(i) for i in range(score_df.shape[0])]

# 添加行索引
data = pd.DataFrame(score, columns=subjects, index=stu)
2.2 DataFrame的属性
  • shape
data.shape

# 结果
(10, 5)
  • index

DataFrame的行索引列表

data.index

# 结果
Index(['同学0', '同学1', '同学2', '同学3', '同学4', '同学5', '同学6', '同学7', '同学8', '同学9'], dtype='object')
  • columns

DataFrame的列索引列表

data.columns

# 结果
Index(['语文', '数学', '英语', '政治', '体育'], dtype='object')
  • values

直接获取其中array的值

data.values

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]])
  • T

转置

data.T

结果

在这里插入图片描述

  • head(5):显示前5行内容

如果不补充参数,默认5行。填入参数N则显示前N行

data.head(5)

在这里插入图片描述

  • tail(5):显示后5行内容

如果不补充参数,默认5行。填入参数N则显示后N行

data.tail(5)
2.3 DatatFrame索引的设置

需求:

在这里插入图片描述

2.3.1 修改行列索引值
stu = ["学生_" + str(i) for i in range(score_df.shape[0])]

# 必须整体全部修改
data.index = stu

注意:以下修改方式是错误的

# 错误修改方式
data.index[3] = '学生_3'
2.3.2 重设索引
  • reset_index(drop=False)
    • 设置新的下标索引
    • drop:默认为False,不删除原来索引,如果为True,删除原来的索引值
# 重置索引,drop=False
data.reset_index()

在这里插入图片描述

# 重置索引,drop=True
data.reset_index(drop=True)
2.3.3 以某列值设置为新的索引
  • set_index(keys, drop=True)
    • keys : 列索引名成或者列索引名称的列表
    • drop : boolean, default True.当做新的索引,删除原来的列

设置新索引案例

1、创建

df = pd.DataFrame({'month': [1, 4, 7, 10],
                    'year': [2012, 2014, 2013, 2014],
                    'sale':[55, 40, 84, 31]})

   month  sale  year
0  1      55    2012
1  4      40    2014
2  7      84    2013
3  10     31    2014

2、以月份设置新的索引

df.set_index('month')
       sale  year
month
1      55    2012
4      40    2014
7      84    2013
10     31    2014

3、设置多个索引,以年和月份

df = df.set_index(['year', 'month'])
df
            sale
year  month
2012  1     55
2014  4     40
2013  7     84
2014  10    31

注:通过刚才的设置,这样DataFrame就变成了一个具有MultiIndex的DataFrame。

3.MultiIndex与Panel

3.1 MultiIndex

MultiIndex是三维的数据结构;

多级索引(也称层次化索引)是pandas的重要功能,可以在Series、DataFrame对象上拥有2个以及2个以上的索引。

3.1.1 multiIndex的特性

打印刚才的df的行索引结果

df.index

MultiIndex(levels=[[2012, 2013, 2014], [1, 4, 7, 10]],
           labels=[[0, 2, 1, 2], [0, 1, 2, 3]],
           names=['year', 'month'])

多级或分层索引对象。

  • 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方法

4. 小结

  • pandas的优势【了解】
    • 增强图表可读性
    • 便捷的数据处理能力
    • 读取文件方便
    • 封装了Matplotlib、Numpy的画图和计算
  • series【知道】
    • 创建
      • pd.Series([], index=[])
      • pd.Series({})
    • 属性
      • 对象.index
      • 对象.values
  • DataFrame【掌握】
    • 创建
      • pd.DataFrame(data=None, index=None, columns=None)
    • 属性
      • shape – 形状
      • index – 行索引
      • columns – 列索引
      • values – 查看值
      • T – 转置
      • head() – 查看头部内容
      • tail() – 查看尾部内容
    • DataFrame索引
      • 修改的时候,需要进行全局修改
      • 对象.reset_index()
      • 对象.set_index(keys)
  • MultiIndex与Panel【了解】
    • multiIndex:
      • 类似ndarray中的三维数组
      • 创建:
        • pd.MultiIndex.from_arrays()
      • 属性:
        • 对象.index
    • panel:
      • pd.Panel(data, items, major_axis, minor_axis)
      • panel数据要是想看到,则需要进行索引到dataframe或者series才可以

三、 基本数据操作

为了更好的理解这些基本操作,我们将读取一个真实的股票数据。关于文件操作,后面在介绍,这里只先用一下API

# 读取文件
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.53
2018-02-26    22.80
2018-02-23    22.88
Name: open, dtype: float64

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

	        open	high	close	low
2018-02-27	23.53	25.88	24.16	23.53
2018-02-26	22.80	23.78	23.53	22.80
2018-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	low
2018-02-27	23.53	24.16	25.88	23.53
2018-02-26	22.80	23.53	23.78	22.80
2018-02-23	22.88	22.82	23.37	22.71
2018-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.03
2015-09-14   -10.02
2016-01-11   -10.02
2015-07-15   -10.02
2015-08-26   -10.01
Name: p_change, dtype: float64
  • 使用series.sort_index()进行排序

与df一致

# 对索引进行排序
data['p_change'].sort_index().head()

2015-03-02    2.62
2015-03-03    1.44
2015-03-04    1.57
2015-03-05    2.02
2015-03-06    8.51
Name: p_change, dtype: float64

4. 总结

  • 1.索引【掌握】
    • 直接索引 – 先列后行,是需要通过索引的字符串进行获取
    • loc – 先行后列,是需要通过索引的字符串进行获取
    • iloc – 先行后列,是通过下标进行索引
    • ix – 先行后列, 可以用上面两种方法混合进行索引
  • 2.赋值【知道】
    • data[“”] = **
    • data.** = **
  • 3.排序【知道】
    • dataframe
      • 对象.sort_values()
      • 对象.sort_index()
    • series
      • 对象.sort_values()
      • 对象.sort_index()

四、 DataFrame运算

1. 算术运算

  • add(other)

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

data['open'].add(1)

2018-02-27    24.53
2018-02-26    23.80
2018-02-23    23.88
2018-02-22    23.25
2018-02-14    22.49
  • sub(other)

2. 逻辑运算

2.1 逻辑运算符号
  • 例如筛选data[“open”] > 23的日期数据
    • data[“open”] > 23返回逻辑结果
data["open"] > 23

2018-02-27     True
2018-02-26    False
2018-02-23    False
2018-02-22    False
2018-02-14    False
# 逻辑判断的结果可以作为筛选的依据
data[data["open"] > 23].head()

在这里插入图片描述

  • 完成多个逻辑判断,
data[(data["open"] > 23) & (data["open"] < 24)].head()

在这里插入图片描述

2.2 逻辑运算函数
  • query(expr)
    • expr:查询字符串

通过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(众数)结果:

countNumber of non-NA observations
sumSum of values
meanMean of values
medianArithmetic median of values
minMinimum
maxMaximum
modeMode
absAbsolute Value
prodProduct of values
stdBessel-corrected sample standard deviation
varUnbiased variance
idxmaxcompute the index labels with the maximum
idxmincompute the index labels with the minimum

对于单个函数去进行统计的时候,坐标轴还是按照默认列“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 累计统计函数
函数作用
cumsum计算前1/2/3/…/n个数的和
cummax计算前1/2/3/…/n个数的最大值
cummin计算前1/2/3/…/n个数的最小值
cumprod计算前1/2/3/…/n个数的积

那么这些累计统计函数怎么用?

在这里插入图片描述

以上这些函数可以对series和dataframe操作

这里我们按照时间的从前往后来进行累计

  • 排序
# 排序之后,进行累计求和
data = data.sort_index()
  • 对p_change进行求和
stock_rise = data['p_change']
# plot方法集成了前面直方图、条形图、饼图、折线图
stock_rise.cumsum()

2015-03-02      2.62
2015-03-03      4.06
2015-03-04      5.63
2015-03-05      7.65
2015-03-06     16.16
2015-03-09     16.37
2015-03-10     18.75
2015-03-11     16.36
2015-03-12     15.03
2015-03-13     17.58
2015-03-16     20.34
2015-03-17     22.42
2015-03-18     23.28
2015-03-19     23.74
2015-03-20     23.48
2015-03-23     23.74

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

在这里插入图片描述

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

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

关于plot,稍后会介绍API的选择

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. 小结

  • 算术运算【知道】
  • 逻辑运算【知道】
    • 1.逻辑运算符号
    • 2.逻辑运算函数
      • 对象.query()
      • 对象.isin()
  • 统计运算【知道】
    • 1.对象.describe()
    • 2.统计函数
    • 3.累积统计函数
  • 自定义运算【知道】
    • apply(func, axis=0)

五、 Pandas画图

1. pandas.DataFrame.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

六、 文件读取与存储

我们的数据大部分存在于文件当中,所以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 )
    • filepath_or_buffer:文件路径
    • sep :分隔符,默认用","隔开
    • usecols:指定读取的列名,列表形式
  • 举例:读取之前的股票的数据
# 读取文件,并且指定只获取'open', 'close'指标
data = pd.read_csv("./data/stock_day.csv", usecols=['open', 'close'])

			open	close
2018-02-27	23.53	24.16
2018-02-26	22.80	23.53
2018-02-23	22.88	22.82
2018-02-22	22.25	22.28
2018-02-14	21.49	21.92
1.2 to_csv
  • DataFrame.to_csv(path_or_buf=None, 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	open
0	2018-02-27	23.53
1	2018-02-26	22.80
2	2018-02-23	22.88
3	2018-02-22	22.25
4	2018-02-14	21.49
5	2018-02-13	21.40
6	2018-02-12	20.70
7	2018-02-09	21.20
8	2018-02-08	21.79
9	2018-02-07	22.69

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

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

2. HDF5

2.1 read_hdf与to_hdf

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

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

    从h5文件当中读取数据

    • path_or_buffer:文件路径
    • key:读取的键
    • return:Theselected object
  • DataFrame.to_hdf(path_or_buf, key, **kwargs)

2.2 案例
  • 读取文件
day_close = pd.read_hdf("./data/day_close.h5")

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

在这里插入图片描述

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

pip install tables

在这里插入图片描述

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=None, orient=None, typ=‘frame’, lines=False)
    • 将JSON格式准换成默认的Pandas DataFrame格式
    • orient : string,Indication of expected JSON string format.
      • ‘split’ : dict like {index -> [index], columns -> [columns], data -> [values]}
        • split 将索引总结到索引,列名到列名,数据到数据。将三部分都分开了
      • ‘records’ : list like [{column -> value}, … , {column -> value}]
        • records 以columns:values的形式输出
      • ‘index’ : dict like {index -> {column -> value}}
        • index 以index:{columns:values}...的形式输出
      • ‘columns’ : dict like {column -> {index -> value}},默认该格式
        • colums 以columns:{index:values}的形式输出
      • ‘values’ : just the values array
        • values 直接输出值
    • lines : boolean, default False
      • 按照每行读取json对象
    • typ : default ‘frame’, 指定转换成的对象类型series或者dataframe
3.2 read_josn 案例
  • 数据介绍

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

{"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}
  • 读取

orient指定存储的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')

结果

[{"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},{"article_link":"https:\/\/local.theonion.com\/mom-starting-to-fear-son-s-web-series-closest-thing-she-1819576697","headline":"mom starting to fear son's web series closest thing she will have to grandchild","is_sarcastic":1},{"article_link":"https:\/\/politics.theonion.com\/boehner-just-wants-wife-to-listen-not-come-up-with-alt-1819574302","headline":"boehner just wants wife to listen, not come up with alternative debt-reduction ideas","is_sarcastic":1},{"article_link":"https:\/\/www.huffingtonpost.com\/entry\/jk-rowling-wishes-snape-happy-birthday_us_569117c4e4b0cad15e64fdcb","headline":"j.k. rowling wishes snape happy birthday in the most magical way","is_sarcastic":0},{"article_link":"https:\/\/www.huffingtonpost.com\/entry\/advancing-the-worlds-women_b_6810038.html","headline":"advancing the world's women","is_sarcastic":0},....]
  • 修改lines参数为True
json_read.to_json("./data/test.json", orient='records', lines=True)

结果

{"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}
{"article_link":"https:\/\/local.theonion.com\/mom-starting-to-fear-son-s-web-series-closest-thing-she-1819576697","headline":"mom starting to fear son's web series closest thing she will have to grandchild","is_sarcastic":1}
{"article_link":"https:\/\/politics.theonion.com\/boehner-just-wants-wife-to-listen-not-come-up-with-alt-1819574302","headline":"boehner just wants wife to listen, not come up with alternative debt-reduction ideas","is_sarcastic":1}
{"article_link":"https:\/\/www.huffingtonpost.com\/entry\/jk-rowling-wishes-snape-happy-birthday_us_569117c4e4b0cad15e64fdcb","headline":"j.k. rowling wishes snape happy birthday in the most magical way","is_sarcastic":0}...

4. 小结

  • pandas的CSV、HDF5、JSON文件的读取【知道】
    • 对象.read_**()
    • 对象.to_**()
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐