Home Backend Development Python Tutorial Python进行数据科学工作的简单入门教程

Python进行数据科学工作的简单入门教程

Jun 06, 2016 am 11:23 AM
python data science

Python拥有着极其丰富且稳定的数据科学工具环境。遗憾的是,对不了解的人来说这个环境犹如丛林一般(cue snake joke)。在这篇文章中,我会一步一步指导你怎么进入这个PyData丛林。

你可能会问,很多现有的PyData包推荐列表怎么样?我觉得对新手来说提供太多的选择可能会受不了。因此这里不会提供推荐列表,我要讨论的范围很窄,只集中于10%的工具,但它们可以完成你90%的工作。当你掌握这些必要的工具后,你就可以浏览PyData工具的长列表了,选择自己接下来要使用的。

值得一提的是,我介绍的这几个工具可以让你完成一个数据科学家日常的绝大部分工作了(比如数据输入输出、数据再加工以及数据分析)。
安装

经常会有人过来和我说“我听说Python很擅长处理数据科学,所以我想学一下。但是安装Python和所有其他模块就耗费了两天时间”。安装Python是很合理的,因为你要用它,但是当你不知道真正需要哪些其他工具时就手动安装所有的PyData工具,这确实是一项大工程啊。所以我强烈反对这样做。

幸运的是,Continuum的一伙人创建了Python发行版Anaconda,它包含了大部分PyData工具包。默认没有的模块也可以轻松地通过GUI安装。这个发行版适用于所有主流平台。这样无需耗费两天安装了,可以直接使用它。
IPython Notebook

Python安装后,大部分人直接启动并开始学习。这很合理,但遗憾的是又大错特错了。我没见过直接在Python命令行中运行Python科学计算环境的(因人而异)。相反,可以使用IPython,特别是IPython Notebook,它们都是特别强大的Python shell,被广泛地使用在PyData领域中。我强烈建议你直接使用IPython Notebook(IPyNB)而不用为其他事所烦扰,你不会后悔的。简而言之,IPyNB是一个通过浏览器访问的Python shell。它允许你混合编辑代码、文本和图形(甚至是交互对象)。本文就是在IPyNB中完成的。在Python的会议中,几乎所有的演讲都使用IPython Notebook。Anaconda中预装了IPyNB,可以直接使用。下面看下它是什么样的:

In [1]:

print('Hello World')
Hello World
Copy after login

IPyNB发展很快——每次在会议中听(IPyNB的)核心开发人员演讲时,我总被他们想出的新功能所震撼。要了解它的一些先进功能,可以看看下面这个关于IPython小工具的简短教程。这些小工具可以让你使用滑动条交互地控制绘图:

In [1]:

from IPython.display import YouTubeVideo
YouTubeVideo('wxVx54ax47s') # 没错,它也可以嵌入youtube视频
Copy after login

Out[1]:
6. IPython Widgets – IPython Notebook Tutorial
Pandas

通常,大家会建议你先学习NumPy(读作num-pie,不是num-pee),一个支持多维数组的库。几年前肯定得这样,但现在我几乎不使用NumPy。因为NumPy越来越成为一个被其他库所使用核心库,这些库通常具有更优雅的接口。因此,Pandas成为了处理数据所主要使用的库。它可以以各种格式(包括数据库)输入输出数据、执行join以及其他SQL类似的功能来重塑数据、熟练地处理缺失值、支持时间序列、拥有基本绘图功能和统计功能,等等还有很多。对它所有的特性来说,肯定有一个学习曲线,但我强烈去建议你先看一下大部分文档。你所投入的时间将使你的数据再加工过程更高效,这会带来上千倍的回报。这里有一些快速技巧会让你胃口大开的:
In [18]:

import pandas as pd
 
df = pd.DataFrame({ 'A' : 1.,
          'B' : pd.Timestamp('20130102'),
          'C' : pd.Series(1, index=list(range(4)), dtype='float32'),
          'D' : pd.Series([1, 2, 1, 2], dtype='int32'),
          'E' : pd.Categorical(["test", "train", "test", "train"]),
          'F' : 'foo' })
Copy after login

In [19]:

Out[19]:

 A B C D E F
0 1 2013-01-02 1 1 test foo
1 1 2013-01-02 1 2 train foo
2 1 2013-01-02 1 1 test foo
3 1 2013-01-02 1 2 train foo
Copy after login

可以通过列名来获取某一列:

In [17]:
 
df.B
Out[17]:
 
0  2013-01-02
1  2013-01-02
2  2013-01-02
3  2013-01-02
Name: B, dtype: datetime64[ns]
 
Compute the sum of D for each category in E:
按E分类,每类对D求和:
In [21]:
 
df.groupby('E').sum().D
Out[21]:
 
E
test   2
train  4
Name: D, dtype: int32
Copy after login

使用NumPy(或者笨重的Matlab)达到同样的目的会很麻烦。

还有非常多的用法。不相信的话可以看一下这个教程“10 minutes to pandas”。上面的例子也来自这个教程。
Seaborn

Matplotlib是Python主要的绘图库。但是,我不建议你直接使用它,原因与开始不推荐你使用NumPy是一样的。虽然Matplotlib很强大,它本身就很复杂,你的图经过大量的调整才能变精致。因此,作为替代,我推荐你一开始使用Seaborn。Seaborn本质上使用Matplotlib作为核心库(就像Pandas对NumPy一样)。我将简短地描述下seaborn的优点。具体来说,它可以:

  1. 默认情况下就能创建赏心悦目的图表。(只有一点,默认不是jet colormap)
  2. 创建具有统计意义的图
  3. 能理解pandas的DataFrame类型,所以它们一起可以很好地工作。

虽然anaconda预装了pandas,却没安装seaborn。可以通过conda install seaborn轻松地安装。
具有统计意义的图
In [5]:

%matplotlib inline # IPython magic to create plots within cells
Copy after login

In [7]:

import seaborn as sns
 
# Load one of the data sets that come with seaborn
tips = sns.load_dataset("tips")
 
sns.jointplot("total_bill", "tip", tips, kind='reg');
Copy after login

20154195429304.jpg (421×423)

如你所见,仅通过一行代码,我们就创建了一个漂亮复杂的统计图,其中包含拥有置信区间的最拟合回归直线、边界图,以及相关系数。使用matplotlib重新绘制这幅图的话需要相当多的(丑陋)代码,包括调用scipy执行线性回归并手动利用线性回归方程绘制直线(我甚至想不出怎么在边界绘图,怎么计算置信区间)。上面和下面的例子都摘自教程“the tutorial on quantitative linear models”。
与Pandas的DataFrame很好地工作

数据有自己的结构。通常我们感兴趣的包含不同的组或类(这种情况下使用pandas中groupby的功能会让人感到很神奇)。比如tips(小费)的数据集是这样的:
In [9]:

tips.head()
Out[9]:
 total_bill tip sex smoker day time size
0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3
2 21.01 3.50 Male No Sun Dinner 3
3 23.68 3.31 Male No Sun Dinner 2
4 24.59 3.61 Female No Sun Dinner 4
Copy after login

我们可能想知道吸烟者给的小费是否与不吸烟的人不同。没有seaborn的话,这需要使用pandas的groupby功能,并通过复杂的代码绘制线性回归直线。使用seaborn的话,我们可以给col参数提供列名,按我们的需要划分数据:
In [11]:

sns.lmplot("total_bill", "tip", tips, col="smoker");
Copy after login

20154195344640.jpg (690×341)

很整洁吧?

随着你研究得越深,你可能想更细粒度地控制这些图表的细节。因为seaborn只是调用了matplotlib,那时你可能会想学习这个库。然而,对绝大部分工作来说我还是喜欢使用seaborn。
总结

这篇文章的想法是通过提供部分包来最大化新手使用Python处理数据科学的效率。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the reason why PS keeps showing loading? What is the reason why PS keeps showing loading? Apr 06, 2025 pm 06:39 PM

PS "Loading" problems are caused by resource access or processing problems: hard disk reading speed is slow or bad: Use CrystalDiskInfo to check the hard disk health and replace the problematic hard disk. Insufficient memory: Upgrade memory to meet PS's needs for high-resolution images and complex layer processing. Graphics card drivers are outdated or corrupted: Update the drivers to optimize communication between the PS and the graphics card. File paths are too long or file names have special characters: use short paths and avoid special characters. PS's own problem: Reinstall or repair the PS installer.

How to solve the problem of loading when PS is started? How to solve the problem of loading when PS is started? Apr 06, 2025 pm 06:36 PM

A PS stuck on "Loading" when booting can be caused by various reasons: Disable corrupt or conflicting plugins. Delete or rename a corrupted configuration file. Close unnecessary programs or upgrade memory to avoid insufficient memory. Upgrade to a solid-state drive to speed up hard drive reading. Reinstalling PS to repair corrupt system files or installation package issues. View error information during the startup process of error log analysis.

How to solve the problem of loading when the PS opens the file? How to solve the problem of loading when the PS opens the file? Apr 06, 2025 pm 06:33 PM

"Loading" stuttering occurs when opening a file on PS. The reasons may include: too large or corrupted file, insufficient memory, slow hard disk speed, graphics card driver problems, PS version or plug-in conflicts. The solutions are: check file size and integrity, increase memory, upgrade hard disk, update graphics card driver, uninstall or disable suspicious plug-ins, and reinstall PS. This problem can be effectively solved by gradually checking and making good use of PS performance settings and developing good file management habits.

How to use mysql after installation How to use mysql after installation Apr 08, 2025 am 11:48 AM

The article introduces the operation of MySQL database. First, you need to install a MySQL client, such as MySQLWorkbench or command line client. 1. Use the mysql-uroot-p command to connect to the server and log in with the root account password; 2. Use CREATEDATABASE to create a database, and USE select a database; 3. Use CREATETABLE to create a table, define fields and data types; 4. Use INSERTINTO to insert data, query data, update data by UPDATE, and delete data by DELETE. Only by mastering these steps, learning to deal with common problems and optimizing database performance can you use MySQL efficiently.

How does PS feathering control the softness of the transition? How does PS feathering control the softness of the transition? Apr 06, 2025 pm 07:33 PM

The key to feather control is to understand its gradual nature. PS itself does not provide the option to directly control the gradient curve, but you can flexibly adjust the radius and gradient softness by multiple feathering, matching masks, and fine selections to achieve a natural transition effect.

Do mysql need to pay Do mysql need to pay Apr 08, 2025 pm 05:36 PM

MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

How to optimize database performance after mysql installation How to optimize database performance after mysql installation Apr 08, 2025 am 11:36 AM

MySQL performance optimization needs to start from three aspects: installation configuration, indexing and query optimization, monitoring and tuning. 1. After installation, you need to adjust the my.cnf file according to the server configuration, such as the innodb_buffer_pool_size parameter, and close query_cache_size; 2. Create a suitable index to avoid excessive indexes, and optimize query statements, such as using the EXPLAIN command to analyze the execution plan; 3. Use MySQL's own monitoring tool (SHOWPROCESSLIST, SHOWSTATUS) to monitor the database health, and regularly back up and organize the database. Only by continuously optimizing these steps can the performance of MySQL database be improved.

What should I do if the PS card is in the loading interface? What should I do if the PS card is in the loading interface? Apr 06, 2025 pm 06:54 PM

The loading interface of PS card may be caused by the software itself (file corruption or plug-in conflict), system environment (due driver or system files corruption), or hardware (hard disk corruption or memory stick failure). First check whether the computer resources are sufficient, close the background program and release memory and CPU resources. Fix PS installation or check for compatibility issues for plug-ins. Update or fallback to the PS version. Check the graphics card driver and update it, and run the system file check. If you troubleshoot the above problems, you can try hard disk detection and memory testing.

See all articles