?str.replace()
Return a copy of S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.
Type: method_descriptor
# Running %env without any arguments
# lists all environment variables
# The line below sets the environment
# variable OMP_NUM_THREADS
%env OMP_NUM_THREADS=4
one = "for the money"
two = "for the show"
three = "to get ready now go cat go"
%who str
The slowest run took 7.29 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 5.5 µs per loop
%%writefile pythoncode.py
import numpy
def append_if_not_exists(arr, x):
if x not in arr:
arr.append(x)
def some_useless_slow_function():
arr = list()
for i in range(10000):
x = numpy.random.randint(0, 10000)
append_if_not_exists(arr, x)
append_if_not_exists(arr, x)
### 13. IPython Magic - %prun: Show how much time your program spent in each function.
Using `%prun statement_name` will give you an ordered table showing you the number of times each internal function was called within the statement, the time each call took as well as the cumulative time of all runs of the function.
```python
%prun some_useless_slow_function()
26324 function calls in 0.556 seconds
Ordered by: internal time
ncalls tottime percall cumtime percall filename:lineno(function)
10000 0.527 0.000 0.528 0.000 <ipython-input-46-b52343f1a2d5>:2(append_if_not_exists)
10000 0.022 0.000 0.022 0.000 {method 'randint' of 'mtrand.RandomState' objects}
1 0.006 0.006 0.556 0.556 <ipython-input-46-b52343f1a2d5>:6(some_useless_slow_function)
6320 0.001 0.000 0.001 0.000 {method 'append' of 'list' objects}
1 0.000 0.000 0.556 0.556 <string>:1(<module>)
1 0.000 0.000 0.556 0.556 {built-in method exec}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
x = range(1000)
y = [i ** 2 for i in x]
plt.plot(x,y)
plt.show();
%config InlineBackend.figure_format = 'retina'
plt.plot(x,y)
plt.show();
阻止最终函数的输出
有时候在最后一行阻止函数的输出是很方便的,例如绘图时。 要做到这一点,你只需在最后添加一个分号。
%matplotlib inline
from matplotlib import pyplot as plt
import numpy
x = numpy.linspace(0, 1, 1000)**1.5
# Here you get the output of the function
plt.hist(x)
(array([ 216., 126., 106., 95., 87., 81., 77., 73., 71., 68.]),
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ]),
<a list of 10 Patch objects>)
# By adding a semicolon at the end, the output is suppressed.
plt.hist(x);
执行Shell命令
从 notebook内部执行shell命令很容易。 你可以使用它来检查工作文件夹中可用的数据集:
!ls *.csv
nba_2016.csv titanic.csv
pixar_movies.csv whitehouse_employees.csv
!pip install numpy
!pip list | grep pandas
Requirement already satisfied (use --upgrade to upgrade): numpy in /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages
pandas (0.18.1)
使用LaTeX的公式
当你在Markdown单元格中编写LaTeX时,使用MathJax将其渲染为公式。
$ P(A \mid B) = \frac{P(B \mid A) \, P(A)}{P(B)} $
运行代码从其他内核在notebook中
如果你喜欢,你可以将来自多个内核的代码组合到一个notebook中。
只需在每个单元的开始处使用IPython Magics以及你的内核的名称就可以使用该内核:
%%bash
%%HTML
%%python2
%%python3
%%ruby
%%perl
%%bash
for i in {1..5}
echo "i is $i"
i is 1
i is 2
i is 3
i is 4
i is 5
安装Jupyter的其他内核
Jupyter的一个很好的功能是能够运行不同语言的内核。 举个例子,这里是如何获取R内核运行。
简单选项:使用Anaconda安装R内核
如果你使用Anaconda来设置你的环境,那么让R工作非常容易。 在终端上运行下面的代码:
conda install -c r r-essentials
较不容易的选项:手动安装R内核
如果你不使用Anaconda,这个过程会更复杂一些。 首先,如果您尚未安装R,则需要安装R。
完成之后,启动R控制台并运行以下命令:
install.packages(c('repr', 'IRdisplay', 'crayon', 'pbdZMQ', 'devtools'))
devtools::install_github('IRkernel/IRkernel')
IRkernel::installspec() # to register the kernel in the current R installation
conda install -c damianavila82 rise
# Or alternatively pip:
pip install RISE
# And then run the following code to install and enable the extension:
jupyter-nbextension install rise --py --sys-prefix
jupyter-nbextension enable rise --py --sys-prefix
Jupyter输出系统
笔记本显示为HTML,单元格输出可以是HTML,因此你可以返回几乎任何内容:视频/音频/图像。
在这个例子中,我用我的资料库中的图像扫描文件夹,并显示其缩略图:
import os
from IPython.display import display, Image
names = [f for f in os.listdir('../images/ml_demonstrations/') if f.endswith('.png')]
for name in names[:5]:
display(Image('../images/ml_demonstrations/' + name, width=100))
Convert notebooks to html file using the File > Download as > HTML Menu option.
Share your notebook file with gists or on github, both of which render the notebooks. See this example.
If you upload your notebook to a github repository, you can use the handy mybinder service to allow someone half an hour of interactive Jupyter access to your repository.
Setup your own system with jupyterhub, this is very handy when you organize mini-course or workshop and don't have time to care about students machines.
Store your notebook e.g. in dropbox and put the link to nbviewer. nbviewer will render the notebook from whichever source you host it.
Use the File > Download as > PDF menu to save your notebook as a PDF. If you're going this route, I highly recommend reading Julius Schulz's excellent article Making publication ready Python notebooks.
Create a blog using Pelican from your Jupyter notebooks.