简体   繁体   English

Jupyter Notebook / Lab导入功能失败

[英]jupyter notebook/lab fails on imported function

I have a boolean subsetting function that works on a pandas dataframe: 我有一个在熊猫数据框上工作的布尔子设置功能:

def operational(df):
    return df[(df['cf'] != 0) & (df['ta'] > 0)]

it works well in a script and in a jupiter notebook, when entered in cell: 当在单元格中输入时,它在脚本和木星笔记本中运行良好:

#df = ...
df2 = operational(df)

However, if I keep function definiton in pick.py and import in to jupyter, things go unexpected. 但是,如果我将函数definiton保留在pick.py并导入到jupyter中,事情将会出乎意料。 It seems upon import of a module jupiter does not reconise the types of variables inside a function: 似乎在导入模块时,木星不会协调函数内部变量的类型:

import pick

pick.operational(df).head()

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-16-374442fd7c0a> in <module>()
      1 import pick
----> 2 pick.operational(df).head()

C:\Users\Евгений\Documents\GitHub\sandbox\pick.py in operational(_df)
     11 
     12 def operational(df):
---> 13     return df[(df['cf'] != 0) & (df['ta'] > 0)]

     14 
     15 

TypeError: 'method' object is not subscriptable

Is importing something to notebook a generally bad idea? 将内容导入笔记本通常不是一个好主意吗? I use jupiter lab, if that matters. 如果重要的话,我使用木星实验室。

Okay, from the comments it sounds like you were expecting the notebook to automatically pick up changes in an imported script. 好的,从注释中听起来好像您希望笔记本计算机自动提取导入脚本中的更改。 By default, Python caches import s, so most of the time changes to imported modules won't get picked up until you restart Python. 默认情况下,Python会缓存import s,因此在大多数情况下,除非重新启动Python,否则对导入的模块所做的更改不会生效。

Fortuitously, Jupyter notebooks run on IPython, which supplies a code reloading cell magic . 幸运的是,Jupyter笔记本在IPython上运行,该代码提供了重新加载单元魔术代码 All you need to do is run: 您需要做的就是运行:

%autoreload 2

in any cell, and your notebook should, from then on, automatically pick up any changes in pick.py as you make them (you still have to save the changes to disk before the reload magic can see them, of course). 在任何单元中,笔记本从那时起应该自动在pick.py拾取所有更改( pick.py ,您仍然必须将更改保存到磁盘上,然后重新加载魔术才能看到它们)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM