【DSW Gallery】Jupyter魔术命令使用技巧

本文涉及的产品
交互式建模 PAI-DSW,5000CU*H 3个月
简介: Jupyter Notebook除了能够执行Python代码之外,还提供一些魔术命令(Magic Command)方便用户简洁地解决标准数据分析中的各种常见问题,本文介绍几个常见的魔术命令使用技巧。

直接使用

请打开Jupyter魔术命令使用技巧,并点击右上角 “ 在DSW中打开” 。

image.png


Jupyter 魔术命令使用技巧

Jupyter Notebook除了能够执行Python代码之外,还提供一些魔术命令(Magic Command)方便用户简洁地解决标准数据分析中的各种常见问题。 魔术命令有两种形式:

  • line magic 由单个%前缀表示并在单行输入上运行
  • cell magic 由双%%前缀表示并在多行输入上运行

魔术命令有很多种,我们可以通过%lsmagic命令查看所有可用的魔术命令:

%lsmagic
Available line magics:
%alias  %alias_magic  %autoawait  %autocall  %automagic  %autosave  %bookmark  %cat  %cd  %clear  %colors  %conda  %config  %connect_info  %cp  %debug  %dhist  %dirs  %doctest_mode  %ed  %edit  %env  %gui  %hist  %history  %killbgscripts  %ldir  %less  %lf  %lk  %ll  %load  %load_ext  %loadpy  %logoff  %logon  %logstart  %logstate  %logstop  %ls  %lsmagic  %lx  %macro  %magic  %man  %matplotlib  %mkdir  %more  %mv  %notebook  %page  %pastebin  %pdb  %pdef  %pdoc  %pfile  %pinfo  %pinfo2  %pip  %popd  %pprint  %precision  %prun  %psearch  %psource  %pushd  %pwd  %pycat  %pylab  %qtconsole  %quickref  %recall  %rehashx  %reload_ext  %rep  %rerun  %reset  %reset_selective  %rm  %rmdir  %run  %save  %sc  %set_env  %store  %sx  %system  %tb  %time  %timeit  %unalias  %unload_ext  %who  %who_ls  %whos  %xdel  %xmode
Available cell magics:
%%!  %%HTML  %%SVG  %%bash  %%capture  %%debug  %%file  %%html  %%javascript  %%js  %%latex  %%markdown  %%perl  %%prun  %%pypy  %%python  %%python2  %%python3  %%ruby  %%script  %%sh  %%svg  %%sx  %%system  %%time  %%timeit  %%writefile
Automagic is ON, % prefix IS NOT needed for line magics.

本文会介绍几个常用魔术命令,其他的魔术命令您可以自己探索

使用魔术命令进行文件操作

您可以通过在代码之前添加%%writefile命令来导出单元格里的内容到文件中

%%writefile script.py
import numpy as np
def random_nparray():
    print(np.random.rand(3,2))
random_nparray()
Writing script.py

用%pycat可以显示指定文件的内容

%pycat script.py
import numpy as np
def random_nparray():
    print(np.random.rand(3,2))
random_nparray()

在Jupyter Notebook中用%run魔术命令来执行python文件

%run script.py
[[0.40436084 0.71671436]
 [0.40652354 0.14977982]
 [0.40079174 0.74159821]]

变量管理

使用%who, %who_ls, %whos命令查看当前Jupyter Notebook中定义的变量及其信息,区别在于展示信息的详略程度

%who_ls
['np', 'random_nparray']
%who
np   random_nparray  
%whos
Variable         Type        Data/Info
--------------------------------------
np               module      <module 'numpy' from '/ho<...>kages/numpy/__init__.py'>
random_nparray   function    <function random_nparray at 0x7f9b183018c8>

可以使用%xdel删除指定的变量

%xdel np
%who
random_nparray   

使用%reset可以清除当前环境中的所有变量

%reset
%who
Interactive namespace is empty.

Kernel环境包管理

使用%pip魔术命令可以管理当前运行的Kernel对应的Python虚拟环境中的包。

使用%pip install安装新的Python包之后,需要重启当前Kernel才会生效。

%pip install tdqm
Looking in indexes: https://mirrors.aliyun.com/pypi/simple/
Collecting tdqm
  Downloading https://mirrors.aliyun.com/pypi/packages/5a/38/58c9e22b95e98666fe29f35e217ab6126a03798dadf3f4f8f3e5f898510b/tdqm-0.0.1.tar.gz (1.4 kB)
  Preparing metadata (setup.py) ... ?25ldone
?25hRequirement already satisfied: tqdm in /home/pai/lib/python3.6/site-packages (from tdqm) (4.64.0)
Requirement already satisfied: importlib-resources in /home/pai/lib/python3.6/site-packages (from tqdm->tdqm) (5.4.0)
Requirement already satisfied: zipp>=3.1.0 in /home/pai/lib/python3.6/site-packages (from importlib-resources->tqdm->tdqm) (3.6.0)
Building wheels for collected packages: tdqm
  Building wheel for tdqm (setup.py) ... ?25ldone
?25h  Created wheel for tdqm: filename=tdqm-0.0.1-py3-none-any.whl size=1319 sha256=a08573330ae5b0310db3fda329c82cbbff6807652542c76933111066cf215eeb
  Stored in directory: /root/.cache/pip/wheels/64/bb/39/82c59ab975b19dc6cc2f99bb6034b69cbbae2f130ac112471d
Successfully built tdqm
Installing collected packages: tdqm
Successfully installed tdqm-0.0.1
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv
Note: you may need to restart the kernel to use updated packages.
%pip show tdqm
Name: tdqm
Version: 0.0.1
Summary: Alias for typos of tqdm
Home-page: https://github.com/tqdm/tqdm
Author: 
Author-email: 
License: MPLv2.0
Location: /home/pai/lib/python3.6/site-packages
Requires: tqdm
Required-by: 
Note: you may need to restart the kernel to use updated packages.

执行时长

使用%time命令可以记录函数的执行时长

import numpy as np
%time np.random.normal(size=10)
CPU times: user 527 µs, sys: 135 µs, total: 662 µs
Wall time: 634 µs
array([ 0.15190477, -0.13989631, -1.94123265,  0.76655039, -1.70196434,
       -0.21320566, -0.30997543,  1.34570534, -0.37875918,  0.30126323])

使用%timeit命令可以通过多次运行来评估代码的执行速度,并产生执行时间的平均值+标准差,我们举个例子:

import numpy as np
%timeit np.random.normal(size=1000)
42.3 µs ± 919 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

当您想要确定代码执行和循环过程的稳定性时,这个命令非常有用。

%pinfo

在下面代码段中,我们可以初始化一个简单的对象,然后用%pinfo来获取它的详细信息。

val = 100
%pinfo val
Type:        int
String form: 100
Docstring:  
int(x=0) -> integer
int(x, base=10) -> integer
Convert a number or string to an integer, or return 0 if no arguments
are given.  If x is a number, return x.__int__().  For floating point
numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string,
bytes, or bytearray instance representing an integer literal in the
given base.  The literal can be preceded by '+' or '-' and be surrounded
by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
Base 0 means to interpret the base from the string as an integer literal.
>>> int('0b100', base=0)
4
相关实践学习
使用PAI-EAS一键部署ChatGLM及LangChain应用
本场景中主要介绍如何使用模型在线服务(PAI-EAS)部署ChatGLM的AI-Web应用以及启动WebUI进行模型推理,并通过LangChain集成自己的业务数据。
机器学习概览及常见算法
机器学习(Machine Learning, ML)是人工智能的核心,专门研究计算机怎样模拟或实现人类的学习行为,以获取新的知识或技能,重新组织已有的知识结构使之不断改善自身的性能,它是使计算机具有智能的根本途径,其应用遍及人工智能的各个领域。 本课程将带你入门机器学习,掌握机器学习的概念和常用的算法。
相关文章
|
5月前
|
Docker Python Windows
1行命令搭建自己的python服务器,docker,安装 jupyter
1行命令搭建自己的python服务器,docker,安装 jupyter
105 0
|
安全 网络安全 双11
【漏洞复现-jupyter_notebook-命令执行】vulfocus/jupyter_notebook-cve_2019_9644
【漏洞复现-jupyter_notebook-命令执行】vulfocus/jupyter_notebook-cve_2019_9644
197 0
【漏洞复现-jupyter_notebook-命令执行】vulfocus/jupyter_notebook-cve_2019_9644
|
存储 IDE 开发工具
9个可以提高Jupyter Notebook开发效率的魔术命令
9个可以提高Jupyter Notebook开发效率的魔术命令
478 0
9个可以提高Jupyter Notebook开发效率的魔术命令
|
Shell 开发者 Python
【DSW Gallery】Jupyter简介
JupyterNotebook是一个用于编写Jupyter Notebook的Python环境。本文介绍Jupyter Notebook的常用使用技巧,包括shell命令,测试运行时间等使用方法。
【DSW Gallery】Jupyter简介
|
1天前
|
机器学习/深度学习 人工智能 数据挖掘
【Python数据挖掘】数据挖掘简介及Jupyter notebook操作介绍(图文解释 超详细)
【Python数据挖掘】数据挖掘简介及Jupyter notebook操作介绍(图文解释 超详细)
75 0
|
1天前
|
Python Windows
Jupyter Notebook的使用
Jupyter Notebook的使用
23 0
|
1天前
|
Ubuntu 网络安全 数据安全/隐私保护
使用SSH隧道将Ubuntu云服务器Jupyter Notebook端口映射到本地
这样,你就成功地将Ubuntu云服务器上的Jupyter Notebook端口映射到本地,使你能够通过本地浏览器访问并使用Jupyter Notebook。
45 1
|
1天前
|
JSON 数据可视化 数据挖掘
适合数据分析的ide---Jupyter Notebook的安装使用
适合数据分析的ide---Jupyter Notebook的安装使用
|
1天前
|
机器学习/深度学习 安全 数据安全/隐私保护
Windows系统安装Jupyter Notebook并实现公网访问内网笔记服务
Windows系统安装Jupyter Notebook并实现公网访问内网笔记服务
|
1天前
|
Linux 数据安全/隐私保护 Python
Linux下远程访问Jupyter Notebook 配置
Linux下远程访问Jupyter Notebook 配置
21 0

热门文章

最新文章