http://blog.csdn.net/pipisorry/article/details/53486777

pandas高级功能:性能优化、面板数据、字符串方法、分类、可视化。

性能优化

对Pandas逐行运算的加速

使用dask对dataframe加速

python -m pip install "dask[complete]"    # Install everything

from dask import dataframe as ddf

# df[new_word_cols] = df[word_cols].applymap(lang.word2idfunc) #方式1
# chunksize = args.file_batch_size // 8 #方式2
npartitions = 4 * multiprocessing.cpu_count() #方式3
df[new_word_cols] = ddf.from_pandas(df[word_cols], npartitions=npartitions) \
    .map_partitions(lambda dds: dds.applymap(lang.word2idfunc)).compute(scheduler='processes')
应用apply函数时,方式3大概比方式1节省至少一半时间。

遍历时间对比:


[Install Dask]

[对Pandas百万级文本进行中文分词加速,看这一篇就足够了]

面板数据

{pandas数据结构有一维Series,二维DataFrame,这是三维Panel}
pandas有一个Panel数据结构,可以将其看做一个三维版的,可以用一个由DataFrame对象组成的字典或一个三维ndarray来创建Panel对象:
import pandas.io.data as web
pdata = pd.Panel(dict((stk, web.get_data_yahoo(stk, '1/1/2009', '6/1/2012')) for stk in ['AAPL', 'GOOG', 'MSFT','DELL']))
Note: stk代表指标,6个指标;三维:stk,company,time.
Panel中的每一项(类似于DataFrame的列)都是一个DataFrame
>>> pdata
<class 'pandas.core.panel.Panel'>
Dimensions: 4 (items) x 868 (major_axis) x 6 (minor_axis)
Items axis: AAPL to MSFT
Major_axis axis: 2009-01-02 00:00:00 to 2012-06-01 00:00:00
Minor_axis axis: Open to Adj Close
>>> pdata = pdata.swapaxes('items', 'minor')
>>>pdata['Adj Close']

三维度ix标签索引

基于ix的标签索引被推广到了三个维度,因此可以选取指定日期或日期范围的所有数据,如下所示:
>>> pdata.ix[:,'6/1/2012',:]
>>>pdata.ix['Adj Close', '5/22/2012':,:]
另一个用于呈现面板数据(尤其是对拟合统计模型)的办法是“堆积式的” DataFrame 形式:
>>> stacked=pdata.ix[:,'5/30/2012':,:].to_frame()
>>>stacked
DataFrame有一个相应的to_panel方法,它是to_frame的逆运算:
>>> stacked.to_panel()
<class 'pandas.core.panel.Panel'>
Dimensions: 6 (items) x 3 (major_axis) x 4 (minor_axis)
Items axis: Open to Adj Close
Major_axis axis: 2012-05-30 00:00:00 to 2012-06-01 00:00:00
Minor_axis axis: AAPL to MSFT
皮皮Blog

字符串方法String Methods

Series is equipped with a set of string processing methods in the strattribute that make it easy to operate on each element of the array, as in thecode snippet below. Note that pattern-matching instr generally usesregularexpressions by default (and insome cases always uses them). See more atVectorized String Methods.

In [71]: s = pd.Series(['A', 'B', 'C', 'Aaba', 'Baca', np.nan, 'CABA', 'dog', 'cat'])In [72]: s.str.lower()
Out[72]:
0       a
1       b
2       c
3    aaba
4    baca
5     NaN
6    caba
7     dog
8     cat
dtype: object

皮皮Blog

分类Categoricals

Since version 0.15, pandas can include categorical data in a DataFrame. For full docs, see thecategorical introduction and theAPI documentation.

In [122]: df = pd.DataFrame({"id":[1,2,3,4,5,6], "raw_grade":['a', 'b', 'b', 'a', 'a', 'e']})

Convert the raw grades to a categorical data type.

In [123]: df["grade"] = df["raw_grade"].astype("category")In [124]: df["grade"]
Out[124]:
0    a
1    b
2    b
3    a
4    a
5    e
Name: grade, dtype: category
Categories (3, object): [a, b, e]

Rename the categories to more meaningful names (assigning to Series.cat.categories is inplace!)

In [125]: df["grade"].cat.categories = ["very good", "good", "very bad"]

Reorder the categories and simultaneously add the missing categories (methods underSeries.cat return a newSeries per default).

In [126]: df["grade"] = df["grade"].cat.set_categories(["very bad", "bad", "medium", "good", "very good"])In [127]: df["grade"]
Out[127]:
0    very good
1         good
2         good
3    very good
4    very good
5     very bad
Name: grade, dtype: category
Categories (5, object): [very bad, bad, medium, good, very good]

Sorting is per order in the categories, not lexical order.

In [128]: df.sort_values(by="grade")
Out[128]: id raw_grade      grade
5   6         e   very bad
1   2         b       good
2   3         b       good
0   1         a  very good
3   4         a  very good
4   5         a  very good

Grouping by a categorical column shows also empty categories.

In [129]: df.groupby("grade").size()
Out[129]:
grade
very bad     1
bad          0
medium       0
good         2
very good    3
dtype: int64

皮皮blog

可视化Plot

DataFrame内置基于matplotlib的绘图功能

In [76]: df['GDP percap'].plot(kind='bar')
In [77]: import matplotlib.pyplot as plt
In [78]: plt.show()

直接绘制

Plotting docs.

In [130]: ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))In [131]: ts = ts.cumsum()In [132]: ts.plot()
Out[132]: <matplotlib.axes._subplots.AxesSubplot at 0xaf49988c>

On DataFrame, plot() is a convenience to plot all of the columns with labels:

In [133]: df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index,.....:                   columns=['A', 'B', 'C', 'D']).....: In [134]: df = df.cumsum()In [135]: plt.figure(); df.plot(); plt.legend(loc='best')
Out[135]: <matplotlib.legend.Legend at 0xaf499d4c>

绘制盒图

Python中有许多可视化模块,最流行的当属matpalotlib库[matplotlib绘图基础]。稍加提及,我们也可选择bokeh和seaborn模块[python高级绘图库seaborn]。

使用matplotlib

# Import the module for plotting
import matplotlib.pyplot asplt
plt.show(df.plot(kind='box'))

使用pandas模块中集成R的ggplot主题来美化图表

要使用ggplot,我们只需要在上述代码中多加一行:

importmatplotlib.pyplotasplt
pd.options.display.mpl_style='default'# Sets the plotting display theme to ggplot2
df.plot(kind='box')

比matplotlib.pyplot主题简洁太多。

更好的是引入seaborn模块

该模块是一个统计数据可视化库:

# Import the seaborn library
import seaborn assns
# Do the boxplot
plt.show(sns.boxplot(df,widths=0.5,color="pastel"))

plt.show(sns.violinplot(df,widths=0.5,color="pastel"))

绘制散点图scatter

df:

age  fat_percent
0    23          9.5
1    23         26.5
2    27          7.8
3    27         17.8
4    39         31.4
5    41         25.9

plt.show(df.plot(kind='scatter', x='age', y='fat_percent'))

Note: 不指定x,y会出错: ValueError: scatter requires and x and y column

绘制直方曲线图

plt.show(sns.distplot(df.ix[:,2],rug=True,bins=15))

绘制其它图

with sns.axes_style("white"):
plt.show(sns.jointplot(df.ix[:,1],df.ix[:,2],kind="kde"))

plt.show(sns.lmplot("Benguet", "Ifugao", df))

from: http://blog.csdn.net/pipisorry/article/details/53486777

ref: 《利用Python进行数据分析》*

利用Python进行数据分析——pandas入门(五)

API Reference

pandas-docs/stable

Notebook Python: Getting Started with Data Analysis

Python数据分析入门

Python and R: Is Python really faster than R?

pandas小记:pandas高级功能相关推荐

  1. 【Pandas】Pandas数据分类

    分类是与统计中的分类变量对应的pandas数据类型.分类变量采用有限的,通常是固定的可能值(类别 ; R中的级别).例如性别,社会阶层,血型,国家归属,观察时间或通过李克特量表评级. 与统计分类变量相 ...

  2. 机器学习之Pandas:Pandas介绍、基本数据操作、DataFrame运算、Pandas画图、文件读取与处、缺失值处理、数据离散化、合并、交叉表和透视表、分组与聚合、案例(超长篇,建议收藏慢慢看)

    文章目录 Pandas 学习目标 1Pandas介绍 学习目标 1 Pandas介绍 2 为什么使用Pandas 3 案例: 问题:如何让数据更有意义的显示?处理刚才的股票数据 给股票涨跌幅数据增加行 ...

  3. Python之Pandas:pandas.read_csv()函数的简介、具体案例、使用方法详细攻略

    Python之Pandas:pandas.read_csv()函数的简介.具体案例.使用方法详细攻略 目录 read_csv()函数的简介 read_csv()函数的简介               ...

  4. Py之pandas:pandas的read_excel()函数中各参数说明及函数使用方法讲解

    Py之pandas:pandas的read_excel()函数中各参数说明及函数使用方法讲解 目录 pandas的read_excel()函数中各参数说明及函数使用方法讲解 read_excel()函 ...

  5. RocketMQ 高级功能介绍

    1. 高级功能 1.1 消息存储 分布式队列因为有高可靠性的要求,所以数据要进行持久化存储. 消息生成者发送消息 MQ收到消息,将消息进行持久化,在存储中新增一条记录 返回ACK给生产者 MQ pus ...

  6. python数据库模块_十二、Python高级功能之Mysql数据库模块

    Python高级功能之Mysql数据库模块 安装python mysql组件 # yum -y install MySQL-python.x86_64 以下根据实例来说明: >>> ...

  7. sql取最大值的那一行_从零学会SQL:SQL高级功能

    一.什么是窗口函数 1.什么是窗口函数? 窗口函数,也叫OLAP函数(Online Analytical Processing,联机分析处理),可以对数据库数据进行实时分析处理. 窗口函数的基本语法如 ...

  8. 使用驱动器f:中的光盘之前需要将其格式化_mac虚拟光驱Daemon Tools高级功能详解—光盘刻录...

    DAEMON Tools是一种紧凑而智能的解决方案,用于在Mac上安装不同类型的虚拟光盘,并允许您创建ISO,MDX和MDS / MDF图像.通过该程序,系统可识别虚拟图像,并允许您像使用普通光盘一样 ...

  9. 实现一个可管理、增发、兑换、冻结等高级功能的代币

    本文首发于深入浅出区块链社区 原文链接:实现一个可管理.增发.兑换.冻结等高级功能的代币 本文主要介绍代币高级功能的实现: 代币管理.代币增发.代币兑换.资产冻结.Gas自动补充. 写在前面 在上一篇 ...

  10. Python之pandas:pandas的get_dummies函数简介(将分类变量转为哑变量)及其使用方法之详细攻略

    Python之pandas:pandas的get_dummies函数简介(将分类变量转为哑变量)及其使用方法之详细攻略 目录 pandas的get_dummies函数简介 pandas.get_dum ...

最新文章

  1. 去除MyEclipse频繁弹出的Update Progress窗口
  2. UA MATH571B 2K析因设计 SAS实践 分数2k析因设计
  3. C语言易错题集 第一部
  4. AOSCP4.1.2 红米Note 4X 2017/10/13 非官方 稳定发布
  5. java判断是否换行_如何检测java中的换行符
  6. OSChina 周日乱弹 —— 快喊爸爸
  7. 钉钉主要是用来打卡的,为什么打卡不能放在首页?
  8. Eclipse maven构建springmvc项目
  9. 全三轨磁条卡读写器|写卡器MSR606的驱动安装与Demo软件测试操作指南
  10. 嵌入式系统开发-麦子学院(2)——开发环境的搭建
  11. 如何在ubuntu22.04上使用微软精英手柄
  12. 深圳杯2020数学建模C题 遗传算法
  13. 智能供应链预测的应用
  14. 多维尺度分析之下不同模型的比较
  15. 条件覆盖,路径覆盖,语句覆盖,分支覆盖
  16. u-boot与linux下网卡MAC地址的更改
  17. Altium Designer中PCB画多层板(4、6、8...层)
  18. CSS如何在宽高不确定的父元素内画一个正方形
  19. [kuangbin带你飞]专题四 最短路练习 R
  20. OpenCV开发笔记(五十八):红胖子8分钟带你深入了解图像的矩(图文并茂+浅显易懂+程序源码)

热门文章

  1. linux软链接和硬链接的区别
  2. 什么是“5个9”(99.999%)的可靠性?
  3. DEDE 文章常用标签
  4. C++中关于指针入门的最好的文章
  5. 37.django基础概念
  6. 巧用 Class Extension 隐藏属性
  7. CSS position属性---absolute与relative
  8. Linux系统中使用netcat命令的奇技淫巧
  9. 使用纯生js实现图片轮换
  10. Thrift之代码生成器Compiler原理及源码详细解析2