I'm using Python 3+ in Jupyter Lab and I'm following this tutorial. Establishing a variable inside a function vs. outside a function makes it work more reliably. Why?
For example, I wanted to execute the following two, but only the first one works as expected:
selected_training_examples = select_and_transform_features(training_examples)
selected_validation_examples = select_and_transform_features(validation_examples)
This is the original function definition works as expected only the first time:
# bucketizing latitude:
LATITUDE_RANGES = zip(range(32, 44), range(33, 45))
def select_and_transform_features(source_df):
selected_examples = pd.DataFrame()
selected_examples["median_income"] = source_df["median_income"]
for r in LATITUDE_RANGES:
selected_examples["latitude_%d_to_%d" % r] = source_df["latitude"].apply(
lambda l: 1.0 if l >= r[0] and l < r[1] else 0.0)
return selected_examples
But if I put LATITUDE_RANGES inside the function definition it works everytime:
def select_and_transform_features(source_df):
# bucketizing latitude:
LATITUDE_RANGES = zip(range(32, 44), range(33, 45))
selected_examples = pd.DataFrame()
selected_examples["median_income"] = source_df["median_income"]
for r in LATITUDE_RANGES:
selected_examples["latitude_%d_to_%d" % r] = source_df["latitude"].apply(
lambda l: 1.0 if l >= r[0] and l < r[1] else 0.0)
return selected_examples
This was a fix I learned from @RadEdje post here. I'm a newbie, so I can't comment and ask directly and I thought formulating this question might be helpful for others to learn.
Researching 'why' led me to think it could be related to the fact that I'm using jupyter labs, this post for example. So, with LATITUDE_RANGES left outside of the function, I tried executing the following in my jupyter notebook:
%reload_ext autoreload
%autoreload 2
However, it didn't have the same effect as moving LATITUDE_RANGES inside the function definition. So my question here is: why would python code work once? I have a lot to learn - what are the keywords which describe this situation? Thanks!