在 Jupyter 中调用定义的函数时命名错误

Wes*_*rld 3 function nameerror python-3.x jupyter-notebook

我正在关注https://blog.patricktriest.com/analyzing-cryptocurrencies-python/ 上的教程,但我有点卡住了。我很想定义一个函数,然后立即调用。

我的代码如下:

def merge_dfs_on_column(dataframes, labels, col):
    '''merge a single column of each dataframe on to a new combined dataframe'''
    series_dict={}
    for index in range(len(dataframes)):
        series_dict[labels[index]]=dataframes[index][col]
    return pd.DataFrame(series_dict)
# Merge the BTC price dataseries into a single dataframe
btc_usd_datasets= merge_dfs_on_column(list(exchange_data.values()),list(exchange_data.keys()),'Weighted Price')
Run Code Online (Sandbox Code Playgroud)

我可以清楚地看到我已经定义了merge_dfs_on_column fucntion,并且我认为语法是正确的,但是,当我在最后一行调用该函数时,出现以下错误:

NameError                                 Traceback (most recent call last)
<ipython-input-22-a113142205e3> in <module>()
      1 # Merge the BTC price dataseries into a single dataframe
----> 2 btc_usd_datasets= merge_dfs_on_column(list(exchange_data.values()),list(exchange_data.keys()),'Weighted Price')

NameError: name 'merge_dfs_on_column' is not defined
Run Code Online (Sandbox Code Playgroud)

我在谷歌上搜索了答案并仔细检查了语法,但我不明白为什么在调用时无法识别该函数。

Dav*_*d A 5

在调用函数之前,Python 解释器不会执行您的函数定义。

仔细检查正在执行的内容和时间。在 Jupyter 中,可以不按输入顺序运行代码,这似乎是您不小心在做的事情。(也许尝试“全部运行”)