Python Data Science Handbook (1) IPython: Beyond Python

1.1 shell or Notebook


Jupyter Notebook is IPython shell browser-based graphical interface that provides a rich set of dynamic display function. Jupyter Notebook can not only execute Python / IPython statement, also allows users to add formatted text, static and dynamic visualization, mathematical formulas, JavaScript plug-ins, and so on. Not only that, but also to share these documents Notebook stored, so others can open these Notebook, Notebook and executes the code into their own systems.

> jupyter notebook  

1.2 IPython help and documentation

Symbol? For browsing documents, ?? symbol for browsing source code, and Tab key can be used to auto-complete.

Python Each object has a reference to the string, the string that is docstring. In most cases, the string contains a brief description of the object and use.

help(len)
Help on built-in function len in module builtins:

len(obj, /)
    Return the number of items in a container.
len?
Signature: len(obj, /)
Docstring: Return the number of items in a container.
Type:      builtin_function_or_method

This method is also applicable to other functions or objects you create yourself!

def square(a):
    """Return the square of a."""
    return a ** 2
    

square?
Signature: square(a)
Docstring: Return the square of a.
Type:      function
square??
Signature: square(a)
Source:   
def square(a):
    """Return the square of a."""
    return a ** 2
Type:      function

?? source code may not be displayed. This is because the object is not implemented in Python, but with extended C language compiler or other language. In this case, ?? suffix will be equivalent to? Suffix.

Use TAB completion object or command.

TAB can be used to view objects in the system may be introduced into the bag or package may be introduced.

Use * for wildcard match.

str.*find*?
str.find
str.rfind

*Warning?
BytesWarning
DeprecationWarning
FutureWarning
ImportWarning
PendingDeprecationWarning
ResourceWarning
RuntimeWarning
SyntaxWarning
UnicodeWarning
UserWarning
Warning

1.3 Shortcuts

Find history with the up and down arrow keys, if you enter def then press the arrow keys, you will find the most recent beginning with def command (if any) in the command history.

  • Ctrl + a Move the cursor to the beginning of the Bank
  • Ctrl + e to move the cursor at the end of the line
  • Ctrl + l clear the terminal screen content
  • Ctrl + c interrupt Python command being executed
  • Ctrl + d exit the current IPython session

1.4 IPython magic command

Magic command has two forms: magic line (line magic), and Magic cells (cell magic). Magic% row single character as a prefix, acting on a single line input; means two magic %% prefixed input acting on multiple lines.

  • % Paste: The paste clipboard code integrity and automatically execute code input result.
%paste
def f(x, y, z):
    return (x+y)/z
a = 5
b = 6
c = 7
result = f(a, b, c)
print(result)

## -- End pasted text --
1.5714285714285714
  • %cpaste也是粘贴文本的,可以粘贴任何一条代码,在输入结束命令之前都不会执行代码,输入‘--’按回车或者使用‘Ctrl-D’停止粘贴代码,停止粘贴代码后会执行代码。
  • %run myscript.py:执行脚本内容,或者使用runfile命令。
#------------------------------------- 
# file: myscript.py 
def square(x): 
    """求平方""" 
    return x ** 2 
for N in range(1, 4): 
    print(N, "squared is", square(N))

  • %timeit:计算一行Python语句执行的时间。
%timeit L = [n ** 2 for n in range(1000)]
416 µs ± 58.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
  • 对于多行语句,可以加入第二个 % 符号将其转变成单元魔法,以处理多行输入。
  • %reset:指删除interactive命名空间中全部的变量名。

  • %xdel variable:删除单个变量的引用。

  • %magic:获取可用魔法函数的通用描述以及一些示例。
  • %lsmagic:获取所有魔法函数的列表。

1.5 输入和输出历史

In[1]:/Out[1]:给出了在当前会话中如何获取输入和输出历史的线索。
In 对象是一个列表,按照顺序记录所有的命令(列表中的第一项是一个占位符,以便 In[1] 可以表示第一条命令)。
Out 对象不是一个列表,而是一个字典。它将输入数字映射到相应的输出(如果有的话)。
任何返回值是 None 的命令都不会加到 Out 变量中。

变量 _(单下划线)用于更新以前的输出,双下划线获得倒数第二个历史输出,三下划线获得倒数第三个历史输出,仅止于此。

Out[X]的简写是_X。

要禁止一个命令的输出,最简单的方式就是在行末尾处添加一个分号。

使用%history魔法命令输出历史记录。

1.6 IPython和shell命令

使用 ! 符号作为前缀在 IPython 中执行任何shell命令行命令。

shell 命令不仅可以从 IPython 中调用,还可以和 IPython 命名空间进行交互。通过一个赋值操纵符可以将任何 shell 命令的输出保存到 Python 中。

需要注意的是这些结果并不以列表的形式返回,而是以 IPython 中定义的一个特殊 shell 返回类型的形式返回。这看上去和 Python 列表很像,并且可以像列表一样操作。但是这种类型还有其他功能,例如 grep 和 fields 方法以及 s、n 和 p 属性,允许我们轻松地搜索、过滤和显示结果。

1.7 与shell相关的魔法命令

自动魔法(automagic)函数:%cd、%cat、%cp、%env、%ls、%man、%mkdir、%more、%mv、%pwd、%rm 和 %rmdir。如果 automagic 被打开,以上任何一个魔法命令都可以省略 % 符号,这使得 IPython 提示符可以被当做当作普通 shell 一样使用。

1.8 错误和调试

改变错误打印信息:

  • %xmode Context:普通(默认)。
  • %xmode Plain:更加紧凑。
  • %xmode Verbose:加入了一些额外的信息,包括任何被调用的函数的参数。

使用%debug开启调试模式。

使用%pbd函数在发生错误时自动打开调试界面。

使用%run -d交互式地运行脚本。 

1.9 代码的分析和计时

  • %time:对单个语句的执行时间进行计时。
  • %timeit:对单个语句的重复执行进行计时,以获得更高的准确度。

有时候重复一个操作并不是最佳选择。例如,如果有一个列表需要排序,我们可能会被重复操作误导。对一个预先排好序的列表进行排序,比对一个无序的列表进行排序要快,所以重复运行将使结果出现偏差,对于这种情况,%time 魔法函数可能是更好的选择。

  • %prun:利用分析器运行代码。
  • %lprun:利用逐行分析器运行代码。
  • %memit:测量单个语句的内存使用。
  • %mprun:通过逐行的内存分析器运行代码。

Guess you like

Origin www.cnblogs.com/dingdangsunny/p/12396911.html