0

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. 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.

Evgeny
  • 4,173
  • 2
  • 19
  • 39
  • 1
    Do you have another method named `df` in the script you are importing to? – Rahul Chawla Jan 21 '19 at 13:06
  • 1
    are you sure you're passing the same `df`? – IanS Jan 21 '19 at 13:07
  • @Rahul Chawla - actually, `pick.operational` worked when I commented out everything, but `operational` definition! Many thanks! Will investigate where `df` drops in namespace in `pick.py`. – Evgeny Jan 21 '19 at 13:11
  • Also looks like I need kernel restart to effectuate imports again too. Simply running a cell with import does not seem to import the latest version of `pick` module. – Evgeny Jan 21 '19 at 13:22
  • looks like a have a case for https://stackoverflow.com/questions/4111640/how-to-reimport-module-to-python-then-code-be-changed-after-import – Evgeny Jan 21 '19 at 14:00
  • @EPo Glad that it helped. – Rahul Chawla Jan 21 '19 at 14:04

1 Answers1

2

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 imports, so most of the time changes to imported modules won't get picked up until you restart Python.

Fortuitously, Jupyter notebooks run on IPython, which supplies a code reloading cell magic. 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).

tel
  • 13,005
  • 2
  • 44
  • 62