IPython notebook:如何编写可以访问笔记本变量的单元魔法? [英] IPython notebook: How to write cell magic which can access notebook variables?

查看:252
本文介绍了IPython notebook:如何编写可以访问笔记本变量的单元魔法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是:如何编写可以访问IPython笔记本命名空间的IPython单元魔法?

My question is: How can I write an IPython cell magic which has access to the namespace of the IPython notebook?

IPython允许编写用户定义的单元格魔法。我的计划是创建一个绘图函数,它可以绘制一个或多个任意Python表达式(基于Pandas Series对象的表达式),其中单元格字符串中的每一行都是图表中的单独图形。

IPython allows writing user-defined cell magics. My plan is creating a plotting function which can plot one or multiple arbitrary Python expressions (expressions based on Pandas Series objects), whereby each line in the cell string is a separate graph in the chart.

这是单元格魔法的代码:

This is the code of the cell magic:

def p(line, cell):
    import pandas as pd
    import matplotlib.pyplot as plt

    df = pd.DataFrame()
    line_list = cell.split('\n')

    counter = 0
    for line in line_list:
        df['series' + str(counter)] = eval(line)      
        counter += 1

    plt.figure(figsize = [20,6])
    ax = plt.subplot(111)
    df.plot(ax = ax)


def load_ipython_extension(ipython):
    ipython.register_magic_function(p, 'cell')

该函数以字符串形式接收整个单元格内容。然后,该字符串由换行符拆分,并使用eval()进行评估。结果将添加到Pandas DataFrame中。最后使用matplotlib绘制DataFrame。

The function receives the entire cell contents as a string. This string is then split by line breaks and evaluated using eval(). The result is added to a Pandas DataFrame. Finally the DataFrame is plotted using matplotlib.

用法示例:首先在IPython笔记本中定义Pandas Series对象。

Usage example: First define the Pandas Series object in IPython notebook.

import pandas as pd
ts = pd.Series([1,2,3])

然后在IPython笔记本中调用魔法(下面的整个代码是一个单元格):

Then call the magic in IPython notebook (whereby the whole code below is one cell):

%%p
ts * 3
ts + 1

这代码失败,出现以下错误:

This code fails with the following error:

NameError: name 'ts' is not defined

我怀疑问题是 p 函数只收到 ts * 3 \ n ts + 1 作为字符串,并且无法访问IPython笔记本的命名空间中定义的 ts 变量(因为 p 函数是在一个单独的.py文件中定义的。)

I suspect the problem is that the p function only receives ts * 3\n ts + 1 as a string and that it does not have access to the ts variable defined in the namespace of IPython notebook (because the p function is defined in a separate .py file).

我的代码如何改变所以cell magic可以访问在$中定义的 ts 变量IPython笔记本(因此不会因NameError而失败)?

How does my code have to be changed so the cell magic has access to the ts variable defined in the IPython notebook (and therefore does not fail with the NameError)?

推荐答案

使用 @needs_local_scope 装饰师装饰。文档有点遗漏,但你可以看到如何使用,欢迎对文档做出贡献。

Use the @needs_local_scope decorator decorator. Documentation is a bit missing, but you can see how it is used, and contributing to docs would be welcome.

这篇关于IPython notebook:如何编写可以访问笔记本变量的单元魔法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆