Pandas知识点概览(python中的pandas的两种基本使用)
一.Pandas介绍
1.1Pandas
以Numpy为基础,借力Numpy模块在计算方面性能高的优势
基于matplotlib,能够简便的画图
独特的数据结构
1.2Pandas优势
便捷的数据处理能力
读取文件方便
封装了matplotlib、 Numpy的画图和计算
1.3DataFrame
1.3.1DataFrame结构
DataFrame对象既有行索引,又有列索引
行索引,表明不同行,横向索引,叫index,0轴,axis=0
列索引,表明不同列,纵向索引,叫columns,1轴,axis=1
1.3.2DataFrame的属性
shape
index:DataFrame的行索引列表
columns:DataFrame的列索引列表
values:直接获取其中array的值
T:转置
head:显示前五行内容
tail:显示后五行内容
1.3.3DataFrame索引的设置
1.3.3.1修改行列索引值
data.index = new_index 复制代码
1.3.3.2重设索引
reset_index(drop=False) # 设置新的下标索引 # drop默认为False,不删除原来索引,如果为True,删除原来的索引值 复制代码
1.3.3.3以某列值设置为新的索引
set_index(keys, drop=True) # keys:列索引名称或者列索引名称的列表 # drop:为True时当做新的索引,删除原来的索引 复制代码
1.4MultiIndex和Panel
1.4.1 MultiIndex
多级或分层索引对象
index属性
names:levels的名称
levels:每个level的元组值
df.index MultiIndex(levels=[[2012, 2013, 2014], [1, 4, 7, 10]], labels=[[0, 2, 1, 2], [0, 1, 2, 3]], names=['year', 'month']) 复制代码
1.4.2 Panel
Class pa das.Panel(data=None, items=None, major_axis=None, minor_axis=None, copy=False, dtype=None)
存储三维数组的Panel结构
1.5 Series结构
seris结构只有行索引
1.5.1 创建series
通过已有数据创建
指定内容,默认索引
pd.Series(np.arrange(10)) 复制代码
指定索引
pd.Seris([1,2,3,4,5], index=[4,5,3,2,1]) 复制代码
通过字典创建
pd.Series({'red':100, ''blue':200, 'green': 500, 'yellow':1000}) 复制代码
1.5.2 series获取属性和值
index
values
二.基本数据操作
2.1索引操作
2.1.1直接使用行列索引(先列后行)
# 直接使用行列索引名字的方式(先列后行) data['open']['2018-02-27'] 23.53 # 不支持的操作 # 错误 data['2018-02-27']['open'] # 错误 data[:1, :2] 复制代码
2.1.2结合loc或者iloc使用索引
# 使用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可以通过索引的下标去获取 # 获取前100天数据的'open'列的结果 data.iloc[0:100, 0:2].head() 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 复制代码
2.1.3使用ix组合索引
# 使用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.2赋值操作
# 直接修改原来的值 data['close'] = 1 # 或者 data.close = 1 复制代码
2.3排序
一种是对于索引进行排序,一种是对于内容进行排序
使用df.sort_values(by=, ascending=)
单个键值或者多个键进行排序,默认升序
ascending=False:降序
ascending=True:升序
# 按照涨跌幅大小进行排序 , 使用ascending指定按照大小排序 data = data.sort_values(by='p_change', ascending=False).head() open high close low volume price_change p_change turnover 2015-08-28 15.40 16.46 16.46 15.00 117827.60 1.50 10.03 4.03 2015-05-21 27.50 28.22 28.22 26.50 121190.11 2.57 10.02 4.15 2016-12-22 18.50 20.42 20.42 18.45 150470.83 1.86 10.02 3.77 2015-08-04 16.20 17.35 17.35 15.80 94292.63 1.58 10.02 3.23 2016-07-07 18.66 18.66 18.66 18.41 48756.55 1.70 10.02 1.67 # 按照过个键进行排序 data = data.sort_values(by=['open', 'high']) open high close low volume price_change p_change turnover 2015-06-15 34.99 34.99 31.69 31.69 199369.53 -3.52 -10.00 6.82 2015-06-12 34.69 35.98 35.21 34.01 159825.88 0.82 2.38 5.47 2015-06-10 34.10 36.35 33.85 32.23 269033.12 0.51 1.53 9.21 2017-11-01 33.85 34.34 33.83 33.10 232325.30 -0.61 -1.77 5.81 2015-06-11 33.17 34.98 34.39 32.51 173075.73 0.54 1.59 5.92 复制代码
使用df.sort_index给索引排序
# 对索引进行排序 data.sort_index() open high close low volume price_change p_change turnover 2015-03-02 12.25 12.67 12.52 12.20 96291.73 0.32 2.62 3.30 2015-03-03 12.52 13.06 12.70 12.52 139071.61 0.18 1.44 4.76 2015-03-04 12.80 12.92 12.90 12.61 67075.44 0.20 1.57 2.30 2015-03-05 12.88 13.45 13.16 12.87 93180.39 0.26 2.02 3.19 2015-03-06 13.17 14.48 14.28 13.13 179831.72 1.12 8.51 6.16 复制代码
使用series.sort_values(ascending=True)进行排序
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()进行排序
# 对索引进行排序 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 复制代码
三.DataFrame运算
3.1算术运算
add(other)
sub(other)
3.2逻辑运算
3.2.1逻辑运算符号
<、>、|、&
3.2.2逻辑运算函数
query(expr)
expr:查询字符串
isin(values)
3.3统计运算
3.3.1describe()
能够直接得出很多统计结果,count,mean,std,min,max等
3.3.2统计函数
count | Number of non-NA observations非空数据的个数 |
---|---|
sum | Sum of values 求和 |
mean | Mean of values 求平均值 |
median | Arithmetic median of values 中位数 |
min | Minimum 最小值 |
max | Maximum 最大值 |
mode | Mode 众数,一组数据中出线最多的那个数 |
abs | Absolute Value 元素的绝对值列表 |
prod | Product of values 所有元素的乘积 |
std | 标准差 |
var | 方差 |
idxmax | 最大元素的索引 |
idxmin | 最小元素的索引 |
对于单个函数去进行统计的时候,坐标轴还是按照这些默认为“columns”(axis=0, default),如果要对行“index”需要指定(axis=1)
3.4累计统计函数
函数 | 作用 |
---|---|
cumsum | 计算和 |
cummax | 求最大值 |
cummin | 求最小值 |
cumprod | 求累乘 |
四.Pandas画图
4.1 pandas.DataFrame.plot
DataFrame.plot(x=None, y=None, kind='line')
'line':line plot(default)折线图
'bar':vertical bar plot垂直方向柱状图
'barh':horizontal bar plot水平方向柱状图
'hist':histogram直方图
'pie':pie plot饼状图
'scatter':scatter plot散点图
x:横轴(可选)列名或列名的数值索引,默认为None,行索引
y:纵轴(可选)列名或列名的数值索引或其列表,默认所有的数据列
kind:str(可选)
4.2 pandas.Series.plot
五.文件读取与存储
5.1 CSV
5.1.1 read_csv
pandas.read_csv(filepath_or_buffer, sep='')
filepath_or_buffer:文件路径
usecols:指定读取的列名,列表形式
# 读取文件,并且指定只获取'open', 'close'指标 data = pd.read_csv("./data/stock_day.csv", usecols=['open', 'close']) open high close 2018-02-27 23.53 25.88 24.16 2018-02-26 22.80 23.78 23.53 2018-02-23 22.88 23.37 22.82 2018-02-22 22.25 22.76 22.28 2018-02-14 21.49 21.99 21.92 复制代码
5.1.2 to_csv
DataFrame.to_csv(path_or_buf=None, sep='', columns=None, header=True, index=True, mode='w', encoding=None)
ath_or_buf:文件路径
sep:数据分割符,默认','
columns:列序列
mode:写入模式,'w':重写,'a':追加
index:是否写入行索引
header:boolean or list of string, default True,是否写入列索引值
5.2 HDF5
5.2.1 read_hdf和to_hdf
HDF5文件的读取和存储需要指定一个键,值为要存储的DataFrame
Pandas.read_hdf(path_or_buf, key=None, **kwargs)
从h5文件当中读取数据
Key:读取的键
return:The selected object
DataFrame.to_hdf(path_or_buf, key, **kwargs)
5.2.2案例
读取文件
day_eps_ttm = pd.read_hdf("./data/stock_data/day/day_eps_ttm.h5") 复制代码
存储文件
day_eps_ttm.to_hdf("./data/test.h5", key="day_eps_ttm") 复制代码
再次读取的时候,需要指定键的名字
new_eps = pd.read_hdf("./data/test.h5", key="day_eps_ttm") 复制代码
5.3 JSON
5.3.1 read_json
pandas.read_json(path_or_buf=None, orient=None, type='frame', lines=False)
按照每行读取json对象
'split':dict like{index->[index], columns->[columns], data->[values]}
'records':list like[{column->value}, ..., {column->value}]
'index':dict like {index->{column->value}}
'columns':dict like{column->{index->value}},默认该格式
'values':just the values array
split将索引总结到索引,列名到列名,数据到数据,将三部分都分开了
records以
columns:values
的形式输出index以
index:{columns:values}...
的形式输出columns以
columns:{index:values}
的形式输出values直接输出值
将JSON格式转换成默认的Pandas DataFrame格式
Orient:string,indication of expected JSON string format
lines:boolean,default False
type:default 'frame',指定转换成的对象类型series或者dataframe
5.3.2 read_json案例
读取
orient指定存储的json格式,lines指定按照行去变成一个样本
json_read = pd.read_json("./data/Sarcasm_Headlines_Dataset.json", orient="records", lines=True) 复制代码
5.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:一个对象存储一行
5.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}... 复制代码
5.4拓展
优先选择使用HDF5文件存储
HDF5在存储的时候支持压缩,使用的方式是blosc,这个是速度最快的也是pandas默认支持的
使用压缩可以提升磁盘利用率,节省空间
DHF5还是跨平台的,可以轻松迁移到hadoop上
六.高级处理-缺失值处理
6.1如何处理nan
判断数据是否为Nan
pd.isnull(df)
pd.notnull(df)
处理方式
删除存在缺失值的:dropna(axis='rows')
替换缺失值:fillna(value, inplace=True)
不会修改原数据,需要接收返回值
value:替换成的值
inplace:True 会修改原数据,False不替换修改原数据,生成新的对象
存在缺失值nan,并且是np.nan
不是缺失值nan,有默认标记的
6.2案例:电影数据的缺失值处理
6.2.1判断缺失值是否存在
np.all(pd.notnull(movie)) 复制代码
6.2.2存在缺失值nan,并且是np.nan
删除
Pandas删除缺失值,使用dropna的前提是,缺失值的类型必须是np.nan
# 不修改原数据 movie.dropna() # 可以定义新的变量接受或者用原来的变量名 data = movie.dropna() 复制代码
替换缺失值
# 替换存在缺失值的样本的两列 # 替换填充平均值,中位数 # movie['Revenue (Millions)'].fillna(movie['Revenue (Millions)'].mean(), inplace=True) 复制代码
替换所有缺失值
for i in movie.columns: if np.all(pd.notnull(movie[i])) == False: print(i) movie[i].fillna(movie[i].mean(), inplace=True) 复制代码
6.2.3不是缺失值nan,有默认标记的
处理思路分析:
先替换'?'为np.nan
# 把一些其它值标记的缺失值,替换成np.nan wis = wis.replace(to_replace='?', value=np.nan) 复制代码
to_replace:替换前的值
value:替换后的值
df.replace(to_replace=,value=)
再进行缺失值的处理
# 删除 wis = wis.dropna() 复制代码
七.高级数据处理-数据离散化
7.1为什么要离散化
连续属性离散化的目的是为了简化数据结构,数据离散化技术可以用来减少给定连续属性值得个数。
7.2什么是数据离散化
连续属性的离散化就是在连续属性的值域上,将值域划分为若干个离散的区间,最后用不同的符号或整数值代表落在每个子区间中的属性值。
7.3股票的涨跌幅离散化
7.3.1读取股票的数据
data = pd.read_csv("./data/stock_day.csv") p_change= data['p_change'] 复制代码
7.3.2将股票涨跌幅数据进行分组
使用的工具
pd.qcut(data, q)
对数据进行分组将数据分组,一般会与value_counts搭配使用,统计每组的个数
series.value_counts():统计分组次数
# 自行分组 qcut = pd.qcut(p_change, 10) # 计算分到每个组数据个数 qcut.value_counts() 复制代码
自定义区间分组
pd.cut(data, bins)
# 自己指定分组区间 bins = [-100, -7, -5, -3, 0, 3, 5, 7, 100] p_counts = pd.cut(p_change, bins) 复制代码
7.3.3股票涨跌幅分组数据变成one-hot编码
什么是one-hot编码
把每个类别生成一个布尔列,这些列中只有一列可以为这个样本取值为1,其又被称为热编码。
Pandas.get_dummies(data, prefix=None)
data:array-like, Series or DataFrame
prefix:分组名字
# 得出one-hot编码矩阵 dummies = pd.get_dummies(p_counts, prefix="rise") 复制代码
八.高级处理-合并
8.1 pd.concat实现数据合并
pd.concat([data1, data2], axis=1)
按照行或列进行合并,axis=0为列索引,axis=1为行索引
8.2 pd.merge
pd.merge(left, right, how='inner', on=None, left_on=None, right_on=None)
left_on = None, right_on = None:指定左右键
Merge method SQL Join Name Description left LEFT OUTER JOIN Use keys from left frame only right RIGHT OUTER JOIN Use keys from right frame only outer FULL OUTER JOIN Use union of keys from both frames inner INNER JOIN Use intersection of keys from both frames8.2.1 pd.merge合并 可以指定按照两组数据的共同键值对合并或者左右各自合并
left
:A DataFrame Objectright
:Another DataFrame objecton
:Columns(names)to join on.Must be found in both the left and right DataFrame objects
8.2.1 pd.merge合并
左连接
result = pd.merge(left, right, how='left', on=['key1', 'key2']) 复制代码
右连接
result = pd.merge(left, right, how='right', on=['key1', 'key2']) 复制代码
外连接
result = pd.merge(left, right, how='outer', on=['key1', 'key2']) 复制代码
九.交叉表和透视表
9.1crosstab-交叉表
交叉表:交叉表用于计算一列数据对于另外一列数据的分组个数(寻找两个列之间的关系)
index:交叉表的行索引(分组数据),可以数组、Series或数组,Series的列表
columns:交叉的列索引(统计数据),可以数组,Series或数组,Series的列表
pd.crosstab(index, columns)
9.2 pivot_table-透视表
透视表:透视表用于计算一类数据对于另外一列数据分组统计,默认统计均值
values:源数据中的列名或一组列名,数据透视表中用于观察分析的数据值
index:源数据中的列名或一组列名,数据透视表用于行索引的数据值
aggfunc:根据当前的行、列索引生成的数据透视表中有多个数据需要进行聚合时,对这多个数据需要进行的操作,默认为np.mean()
DataFrame.pivol_table(values=None, index=None, aggfunc='mean')
十.高级处理-分组与聚合
分组API
key:分组的列数据,可以多个
DataFrame.groupby(key, as_index=False)
案例:
对星巴克数据进行分组聚合
# 导入星巴克店的数据 starbucks = pd.read_csv("./data/starbucks/directory.csv") # 按照国家分组,求出每个国家的星巴克零售店数量 count = starbucks.groupby(['Country']).count()
作者:RIP_Mamba
链接:https://juejin.cn/post/7028735704545329188