centos7.2 wordpress,南京seo网站管理,91色做爰网站,深圳中装建设集团网站pandas
优势#xff1a;
增强图表可读性便捷的数据处理能力读取文件方便封装了Matplotlib、Numpy的画图和计算
更详细的教程#xff1a;Pandas 教程 | 菜鸟教程 (runoob.com)
Pandas数据结构
Pandas中一共有三种数据结构#xff0c;分别为#xff1a;Series、DataFram…pandas
优势
增强图表可读性便捷的数据处理能力读取文件方便封装了Matplotlib、Numpy的画图和计算
更详细的教程Pandas 教程 | 菜鸟教程 (runoob.com)
Pandas数据结构
Pandas中一共有三种数据结构分别为Series、DataFrame和MultiIndex老版本中叫Panel 。
其中Series是一维数据结构DataFrame是二维的表格型数据结构MultiIndex是三维的数据结构。
Series
Series是一个类似于一维数组的数据结构它能够保存任何类型的数据比如整数、字符串、浮点数等主要由一组数据和与之相关的索引两部分构成。 Series的创建
# 导入pandas
import pandas as pd
pd.Series(dataNone, indexNone, dtypeNone)参数
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])通过字典数据创建
color_count pd.Series({red:100, blue:200, green: 500, yellow:1000})
color_countSeries的属性
Series中提供了两个属性index和values
index
color_count.index
# 结果
Index([blue, green, red, yellow], dtypeobject)values
color_count.values
# 结果
array([ 200, 500, 100, 1000])也可以使用索引来获取数据
color_count[2]
# 结果
100DataFrame
DataFrame是一个类似于二维数组或表格(如excel)的对象既有行索引又有列索引 行索引表明不同行横向索引叫index0轴axis0 列索引表名不同列纵向索引叫columns1轴axis1 DataFrame的创建
# 导入pandas
import pandas as pd
pd.DataFrame(dataNone, indexNone, columnsNone)参数
index行标签。如果没有传入索引参数则默认会自动创建一个从0-N的整数索引。
columns列标签。如果没有传入索引参数则默认会自动创建一个从0-N的整数索引。
通过已有数据创建,举个例子
pd.DataFrame(np.random.randn(2,3))例子创建学生成绩表
# 生成10名同学5门功课的数据
score np.random.randint(40, 100, (10, 5))
# 使用Pandas中的数据结构
score_df pd.DataFrame(score)增加行、列索引
# 构造行索引序列
subjects [语文, 数学, 英语, 政治, 体育]
# 构造列索引序列
stu [同学 str(i) for i in range(score_df.shape[0])]
# 添加行索引
data pd.DataFrame(score, columnssubjects, indexstu)DataFrame的属性 shape index columns values T shape
data.shape
# 结果
(10, 5)index
DataFrame的行索引列表
data.index
# 结果
Index([同学0, 同学1, 同学2, 同学3, 同学4, 同学5, 同学6, 同学7, 同学8, 同学9], dtypeobject)columns
DataFrame的列索引列表
data.columns
# 结果
Index([语文, 数学, 英语, 政治, 体育], dtypeobject)values
直接获取其中array的值
data.valuesarray([[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
显示前n行
data.head(n)显示后n行
data.tail(n)ps如果不加参数默认是显示前5行或者后五行。
DatatFrame索引的设置
修改行列索引值
注意只能整行整列得修改
stu [学生_ str(i) for i in range(score_df.shape[0])]
# 必须整体全部修改
data.index stu重设索引
reset_index(dropFalse) 设置新的下标索引drop:默认为False不删除原来索引如果为True,删除原来的索引值
# 重置索引,dropFalse
data.reset_index()# 重置索引,dropTrue
data.reset_index(dropTrue)以某列值设置为新的索引
set_index(keys, dropTrue) keys : 列索引名成或者列索引名称的列表drop : boolean, default True.当做新的索引删除原来的列
1.创建
df pd.DataFrame({month: [1, 4, 7, 10],
year: [2012, 2014, 2013, 2014],
sale:[55, 40, 84, 31]})2.以月份设置新的索引
df.set_index(month)3.设置多个索引以年和月份
df df.set_index([year, month])MultiIndex与Panel
MultiIndex
MultiIndex是三维的数据结构;
多级索引也称层次化索引是pandas的重要功能可以在Series、DataFrame对象上拥有2个以及2个以上的索引。
multiIndex的特性
打印刚才的df的行索引结果
df.index多级或分层索引对象。
index属性 names:levels的名称levels每个level的元组值
df.index.names
# FrozenList([year, month])
df.index.levels
# FrozenList([[1, 2], [1, 4, 7, 10]])multiIndex的创建
arrays [[1, 1, 2, 2], [red, blue, red, blue]]
pd.MultiIndex.from_arrays(arrays, names(number, color))Panel
panel的创建
class pandas.Panel (dataNone, itemsNone, major_axisNone, minor_axisNone) 作用存储3维数组的Panel结构参数 data : ndarray或者dataframeitems : 索引或类似数组的对象axis0major_axis : 索引或类似数组的对象axis1minor_axis : 索引或类似数组的对象axis2
p pd.Panel(datanp.arange(24).reshape(4,3,2),
itemslist(ABCD),
major_axispd.date_range(20130101, periods3),
minor_axis[first, second])查看panel数据
p[:,:,first]
p[B,:,:]基本数据操作
导入数据数据放在上方的资源中了
# 读取文件
data pd.read_csv(./stock_day.csv)
# 删除一些列让数据更简单些再去做后面的操作
data data.drop([ma5,ma10,ma20,v_ma5,v_ma10,v_ma20], axis1)索引操作
直接使用行列索引**(先列后行)**
# 直接使用行列索引名字的方式先列后行
data[open][2018-02-27]# 不支持的操作
# 错误
data[2018-02-27][open]只能先行后列
结合loc或者iloc使用索引
获取从’2018-02-27’:‘2018-02-22’open’的结果
# 使用loc:只能指定行列索引的名字
data.loc[2018-02-27:2018-02-22, open]# 使用iloc可以通过索引的下标去获取
# 获取前3天数据,前5列的结果
data.iloc[:3, :5]使用ix组合索引
获取行第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])]赋值操作
对DataFrame当中的close列进行重新赋值为1
# 直接修改原来的值
data[close] 1
# 或者
data.close 1排序
排序有两种形式一种对于索引进行排序一种对于内容进行排序 使用df.sort_values(by, ascending)单个键或者多个键进行排序, 参数by指定排序参考的键ascending:默认升序 ascendingFalse:降序ascendingTrue:升序
# 按照开盘价大小进行排序 , 使用ascending指定按照大小排序
data.sort_values(byopen, ascendingTrue).head()# 按照多个键进行排序
data.sort_values(by[open, high])# 对索引进行排序
data.sort_index()Series排序
使用series.sort_values(ascendingTrue)进行排序
series排序时只有一列不需要参数
data[p_change].sort_values(ascendingTrue).head()使用series.sort_index()进行排序
与df一致
# 对索引进行排序
data[p_change].sort_index().head()总结
1.索引 直接索引 – 先列后行,是需要通过索引的字符串进行获取loc – 先行后列,是需要通过索引的字符串进行获取iloc – 先行后列,是通过下标进行索引ix – 先行后列, 可以用上面两种方法混合进行索引 2.赋值 data[“”] **data. 3.排序 dataframe 对象.sort_values()对象.sort_index() series 对象.sort_values()对象.sort_index()
DataFrame运算
算术运算
add(other)
比如进行数学运算加上具体的一个数字
data[open].add(1)sub(other)’
逻辑运算(可用于筛选)
逻辑运算符号
例如筛选data[“open”] 23的日期数据 data[“open”] 23返回逻辑结果
data[open] 23# 逻辑判断的结果可以作为筛选的依据
data[data[open] 23].head()完成多个逻辑判断
data[(data[open] 23) (data[open] 24)].head()逻辑运算函数
query(expr) expr:查询字符串
通过query使得刚才的过程更加方便简单
data.query(open24 open23).head()isin(values)
例如判断’open’是否为23.53和23.85
# 可以指定值进行一个判断从而进行筛选操作
data[data[open].isin([23.53, 23.85])]统计运算
describe
综合分析: 能够直接得出很多统计结果, count , mean , std , min , max 等
# 计算平均值、标准差、最大值、最小值
data.describe()统计函数
Numpy当中已经详细介绍在这里我们演示min(最小值), max(最大值), mean(平均值), median(中位数), var(方差), std(标准差),mode(众数)结果:
对于单个函数去进行统计的时候坐标轴还是按照默认列**“columns” (axis0, default)如果要对行“index”** 需要指定**(axis1)**
max()、min()
# 使用统计函数0 代表列求结果 1 代表行求统计结果
data.max(0)std()、var()
# 方差
data.var(0)# 标准差
data.std(0)median()中位数
中位数为将数据从小到大排列在最中间的那个数为中位数。如果没有中间数取中间两个数的平均值。
df pd.DataFrame({COL1 : [2,3,4,5,4,2],
COL2 : [0,1,2,3,4,2]})
df.median()idxmax()、idxmin()
# 求出最大值的位置
data.idxmax(axis0)# 求出最小值的位置
data.idxmin(axis0)累计统计函数
函数作用cunsum计算前n个数的和cunmax计算前n个数的最大值cunmin计算前n个数的最小值cunprod计算前n个数的积
这里我们按照时间的从前往后来进行累计
排序
# 排序之后进行累计求和
data data.sort_index()对p_change进行求和
stock_rise data[p_change]
# plot方法集成了前面直方图、条形图、饼图、折线图
stock_rise.cumsum()如果要使用plot函数需要导入matplotlib.
import matplotlib.pyplot as plt
# plot显示图形
stock_rise.cumsum().plot()
# 需要调用show才能显示出结果
plt.show()自定义运算
apply(func, axis0) func:自定义函数axis0:默认是列axis1为行进行运算 定义一个对列最大值-最小值的函数
data[[open, close]].apply(lambda x: x.max() - x.min(), axis0)小结
算术运算逻辑运算 1.逻辑运算符号2.逻辑运算函数 对象.query()对象.isin() 统计运算 1.对象.describe()2.统计函数3.累积统计函数 自定义运算 apply(func, axis0)
Pandas画图
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
pandas.Series.plot
文件读取与存储
我们的数据大部分存在于文件当中所以pandas会支持复杂的IO操作pandas的API支持众多的文件格式如CSV、SQL、XLS、JSON、HDF5。
ps最常用的HDF5和CSV文件 CSV
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])to_csv DataFrame.to_csv(path_or_bufNone, sep, ’, columnsNone, headerTrue, indexTrue, mode‘w’, encodingNone) path_or_buf :文件路径 sep :分隔符默认用,隔开 columns :选择需要的列索引 header :boolean or list of string, default True,是否写进列索引值 index:是否写进行索引 mode:‘w’重写, ‘a’ 追加 举例保存读取出来的股票数据 保存’open’列的数据然后读取查看结果
# 选取10行数据保存,便于观察数据
data[:10].to_csv(./test.csv, columns[open])#读取查看结果
pd.read_csv(./test.csv)会发现将索引存入到文件当中变成单独的一列数据。如果需要删除可以指定index参数,删除原来的文件重新保存一次。
# index:存储不会讲索引值变成一列数据
data[:10].to_csv(./test.csv, columns[open], indexFalse)HDF5
read_hdf与to_hdf
HDF5文件的读取和存储需要指定一个键值为要存储的DataFrame pandas.read_hdf(path_or_bufkey None** kwargs) 从h5文件当中读取数据 path_or_buffer:文件路径key:读取的键return:Theselected object DataFrame.to_hdf(path_or_buf, key, **kwargs) 读取文件
day_close pd.read_hdf(./day_close.h5)如果读取的时候出现错误
需要安装安装tables模块避免不能读取HDF5文件
pip install tables存储文件
day_close.to_hdf(./data/test.h5, keyday_close)再次读取的时候, 需要指定键的名字
new_close pd.read_hdf(./data/test.h5, keyday_close)注意优先选择使用HDF5文件存储
HDF5在存储的时候支持压缩使用的方式是blosc这个是速度最快的也是pandas默认支持的使用压缩可以提磁盘利用率节省空间HDF5还是跨平台的可以轻松迁移到hadoop 上面
JSON
JSON是我们常用的一种数据交换格式前面在前后端的交互经常用到也会在存储的时候选择这种格式。所以我们需要知道Pandas如何进行读取和存储JSON格式
read_json pandas.read_json(path_or_bufNone, orientNone, typ‘frame’, linesFalse) 将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 以 columnsvalues 的形式输出 ‘index’ : dict like {index - {column - value}} index 以 index{columnsvalues}… 的形式输出 ‘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
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, orientrecords, linesTrue)to_json
DataFrame.to_json(path_or_bufNone, orientNone, linesFalse) 将Pandas 对象存储为json格式path_or_bufNone文件地址orient:存储的json形式{‘split’,’records’,’index’,’columns’,’values’}lines:一个对象存储为一行
案例
存储文件
json_read.to_json(./data/test.json, orientrecords)结果
[{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 sons 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 worlds women,is_sarcastic:0},....]修改lines参数为True
json_read.to_json(./data/test.json, orientrecords, linesTrue)结果
{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 fearsons 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}...
高级处理**-**缺失值处理
isnull判断是否有缺失数据NaNfillna实现缺失值的填充dropna实现缺失值的删除replace实现数据的替换
如何处理nan
获取缺失值的标记方式(NaN或者其他标记方式)如果缺失值的标记方式是NaN 判断数据中是否包含NaN pd.isnull(df),pd.notnull(df) 存在缺失值nan: 1、删除存在缺失值的:dropna(axis‘rows’) 注不会修改原数据需要接受返回值 2、替换缺失值:fillna(value, inplaceTrue) value:替换成的值inplace:True:会修改原数据False:不替换修改原数据生成新的对象 如果缺失值没有使用NaN标记比如使用 先替换‘?’为np.nan然后继续处理
电影数据的缺失值处理
电影数据文件获取
# 读取电影数据
movie pd.read_csv(./data/IMDB-Movie-Data.csv)判断缺失值是否存在
pd.notnull()
pd.notnull(movie)np.all(pd.notnull(movie))存在缺失值nan,并且是np.nan
1、删除
pandas删除缺失值使用dropna的前提是缺失值的类型必须是np.nan
# 不修改原数据
movie.dropna()
# 可以定义新的变量接受或者用原来的变量名
data movie.dropna()2、替换缺失值
# 替换存在缺失值的样本的两列
# 替换填充平均值中位数
# movie[Revenue (Millions)].fillna(movie[Revenue (Millions)].mean(), inplaceTrue)替换所有缺失值
for i in movie.columns:if np.all(pd.notnull(movie[i])) False:print(i)movie[i].fillna(movie[i].mean(), inplaceTrue)不是缺失值nan有默认标记的
wis pd.read_csv(https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data)以上数据在读取时可能会报如下错误
URLError: urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)解决办法
# 全局取消证书验证
import ssl
ssl._create_default_https_context ssl._create_unverified_context处理思路分析
1、先替换‘?’为np.nan df.replace(to_replace, value) to_replace:替换前的值value:替换后的值
# 把一些其它值标记的缺失值替换成np.nan
wis wis.replace(to_replace?, valuenp.nan)2、在进行缺失值的处理
# 删除
wis wis.dropna()高级处理**-**数据离散化
什么是数据的离散化
连续属性的离散化就是在连续属性的值域上将值域划分为若干个离散的区间最后用不同的符号或整数 值代表落在每个子区间中的属性值。
读取股票的数据
先读取股票的数据筛选出p_change数据
data pd.read_csv(./stock_day.csv)
p_change data[p_change]将股票涨跌幅数据进行分组
使用的工具 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)将股票涨跌幅数据进行分组
使用的工具
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)股票涨跌幅分组数据变成one-hot编码
什么是one-hot编码
把每个类别生成一个布尔列这些列中只有一列可以为这个样本取值为1.其又被称为独热编码。
pandas.get_dummies(data, prefixNone) data:array-like, Series, or DataFrameprefix:分组名字
# 得出one-hot编码矩阵
dummies pd.get_dummies(p_counts, prefixrise)高级处理-合并
如果你的数据由多张表组成那么有时候需要将不同的内容合并在一起分析
pd.concat实现数据合并
pd.concat([data1, data2], axis1) 按照行或列进行合并,axis0为列索引axis1为行索引
# 按照行索引进行
pd.concat([data, dummies], axis1)pd.merge
pd.merge(left, right, how‘inner’, onNone) 可以指定按照两组数据的共同键值对合并或者左右各自left : DataFrameright : 另一个DataFrameon : 指定的共同键how:按照什么方式连接
pd.merge合并
left pd.DataFrame({key1: [K0, K0, K1, K2],
key2: [K0, K1, K0, K1],
A: [A0, A1, A2, A3],
B: [B0, B1, B2, B3]})
right pd.DataFrame({key1: [K0, K1, K1, K2],
key2: [K0, K0, K0, K0],
C: [C0, C1, C2, C3],
D: [D0, D1, D2, D3]})
# 默认内连接
result pd.merge(left, right, on[key1, key2])左连接
result pd.merge(left, right, howleft, on[key1, key2])右连接
result pd.merge(left, right, howright, on[key1, key2])外链接
result pd.merge(left, right, howouter, on[key1, key2])pd.concat([数据1, 数据2], axis**)pd.merge(left, right, how, on) how – 以何种方式连接on – 连接的键的依据是哪几个
高级处理-交叉表与透视表
交叉表与透视表什么作用
探究股票的涨跌与星期几有关
以下图当中表示week代表星期几1,0代表这一天股票的涨跌幅是好还是坏里面的数据代表比例可以理解为所有时间为星期一等等的数据当中涨跌幅好坏的比例 交叉表交叉表用于计算一列数据对于另外一列数据的分组个数**(用于统计分组频率的特殊透视表)** pd.crosstab(value1, value2) 透视表透视表是将原有的DataFrame的列分别作为行索引和列索引然后对指定的列应用聚集函数 data.pivot_table(DataFrame.pivot_table([], index[])
数据准备 准备两列数据星期数据以及涨跌幅是好是坏数据 进行交叉表计算
# 寻找星期几跟股票张得的关系
# 1、先把对应的日期找到星期几
date pd.to_datetime(data.index).weekday
data[week] date# 2、假如把p_change按照大小去分个类0为界限
data[posi_neg] np.where(data[p_change] 0, 1, 0)# 通过交叉表找寻两列数据的关系
count pd.crosstab(data[week], data[posi_neg])但是我们看到count只是每个星期日子的好坏天数并没有得到比例该怎么去做
对于每个星期一等的总天数求和运用除法运算求出比例
# 算数运算先求和
sum count.sum(axis1).astype(np.float32)
# 进行相除操作得出比例
pro count.div(sum, axis0)查看效果
使用plot画出这个比例使用stacked的柱状图
pro.plot(kindbar, stackedTrue)
plt.show()使用pivot_table(透视表)实现
使用透视表刚才的过程更加简单
# 通过透视表将整个过程变成更简单一些
data.pivot_table([posi_neg], indexweek)高级处理-分组与聚合
分组与聚合通常是分析数据的一种方式通常与一些统计函数一起使用查看数据的分组情况 分组API
DataFrame.groupby(key, as_indexFalse) key:分组的列数据可以多个 案例:不同颜色的不同笔的价格数据
col pd.DataFrame({color: [white,red,green,red,green], object: [pen,pencil,pencil,ashtray,pen],price1:[5.56,4.20,1.30,0.56,2.75],price2:[4.75,4.12,1.60,0.75,3.15]})进行分组对颜色分组price进行聚合
# 分组求平均值
col.groupby([color])[price1].mean()
col[price1].groupby(col[color]).mean()# 分组数据的结构不变col.groupby([color], as_indexFalse)[price1].mean()星巴克零售店铺数据
现在我们有一组关于全球星巴克店铺的统计数据如果我想知道美国的星巴克数量和中国的哪个多或者我想知道中国每个省份星巴克的数量的情况那么应该怎么办
数据获取
从文件中读取星巴克店铺数据
# 导入星巴克店的数据
starbucks pd.read_csv(./data/starbucks/directory.csv)进行分组聚合
# 按照国家分组求出每个国家的星巴克零售店数量
count starbucks.groupby([Country]).count()画图显示结果
count[Brand].plot(kindbar, figsize(20, 8))
plt.show()假设我们加入省市一起进行分组
# 设置多个索引set_index()
starbucks.groupby([Country, State/Province]).count()