IPython Notebook概览¶
本部分内容更适合在交互模式下阅读,因此,如果你已经安装并运行Ipython Notebook的话,体验会更好。你可以运行以下命令来使用IPython Notebook
ipython notebook
First, we need to explain how to run cells. Try to run the cell below!
import pandas as pd
print "Hi! This is a cell. Press the ▶ button above to run it"
Hi! This is a cell. Press the ▶ button above to run it
当然,你也可以用Ctrl+Enter来运行一个代码框里的内容。亲自试一试~
IPython notebook最有用的功能之一是tab自动补全。
试一下:鼠标单击下面代码框, 把光标移到read_csv(后面,然后按下Shift+Tab
pd.read_csv(
第一次用Shift+Tab,你可以看到下图
第二次后可以看到这样子:
使用四次后,一个更大的提示框会出现在屏幕下端,显示的是read_csv函数的完整文档信息:
这玩意相当好用,总结起来就是“越是不知道这个函数干嘛的,就越要按Shift+Tab”,大不了按上12次......@_@
Okay,接下来试试函数名的补全~
pd.r
按下Tab之后可以看到下图:
写代码¶
在notebook里写代码是再方便不过的了
def print_10_nums():
for i in range(10):
print i,
print_10_nums()
0 1 2 3 4 5 6 7 8 9
保存¶
最新版本的Notebook会自动保存文档,所以,强烈建议你更新到最新的版本!
魔法函数¶
IPython有各种各样内置的魔法函数。例如,可以用%time来测试分别用生成器和列表计算sum()求和效率。
%time sum([x for x in range(100000)])
CPU times: user 15 ms, sys: 3.26 ms, total: 18.2 ms Wall time: 18.5 ms
4999950000
%time sum(x for x in range(100000))
CPU times: user 15.1 ms, sys: 3.99 ms, total: 19.1 ms Wall time: 14.5 ms
4999950000
我最常用的魔法函数是%time和%prun。你可以试着跑一下%magic,查看所有的魔法函数,或者是用%quickref来看看相应的文档
The magics I use most are %time and %prun for profiling. You can run %magic to get a list of all of them, and %quickref for a reference sheet.
%quickref
此外,你还可以通过使用魔法函数来跑Perl的代码。此外跑%%cython代码的时候,相当爽,不过你需要先安装它。
%%perl
$_ = "whoa, python!";
s/python/perl/;
print
whoa, perl!
OK,本部分到此为止~