【问题标题】:Name Error despite having defined it earlier?尽管之前已经定义了名称错误?
【发布时间】:2020-05-09 01:21:08
【问题描述】:
def categorise_sourceIP(df):
    df_sIPf = pd.df.sourceIP.value_counts()
    df_sIPf['counts'] = np.array(df.sourceIP.value_counts())
    df_sIPf['sourceIP'] = df_sIPf.index
    df_sIPf.reset_index(level=0,inplace=True,drop=True)
    counts_cate = []
    for num in df_sIPf['counts']:
        if num in range(0,21):
            counts_cate.append('<20')
        elif num in range(21,201):
                counts_cate.append('21-200')
        elif num in range(201,401):
            counts_cate.append('201-400')
        elif num > 400:
            counts_cate.append('>400')
counts_cate=df_sIPf['categorised_count']

错误回调如下

NameError                                 Traceback (most recent call last)
<ipython-input-11-9622f76efabe> in <module>
     27         elif num > 400:
     28             counts_cate.append('>400')
---> 29 counts_cate=df_sIPf['categorised_count']

NameError: name 'df_sIPf' is not defined

我该如何解决这个问题?在我的问题集中的关键阶段。 本质上是试图在数据帧中的两个不同变量的集群之间建立关系,以便为第二组编写类似的代码。

【问题讨论】:

  • 你的赋值语句在你的函数定义之外

标签: python error-handling syntax-error cluster-analysis


【解决方案1】:

如果您希望在该函数之外可以访问它,则需要从您的函数中返回 df_sIPf

def categorise_sourceIP(df):
    df_sIPf = pd.df.sourceIP.value_counts()
    df_sIPf['counts'] = np.array(df.sourceIP.value_counts())
    df_sIPf['sourceIP'] = df_sIPf.index
    df_sIPf.reset_index(level=0,inplace=True,drop=True)
    counts_cate = []
    for num in df_sIPf['counts']:
        if num in range(0,21):
            counts_cate.append('<20')
        elif num in range(21,201):
                counts_cate.append('21-200')
        elif num in range(201,401):
            counts_cate.append('201-400')
        elif num > 400:
            counts_cate.append('>400')
    return df_sIPf

counts_cate = categorise_sourceIP(df)['categorised_count']

【讨论】:

  • return' 外部函数-我该如何处理这个错误?
  • 模块 'pandas' 没有属性 'df' - 进一步的错误即将到来!
  • re: return outside function,你得把return放在函数里面。
  • re df,您的函数将数据框作为其输入,对吧?您需要提供。
猜你喜欢
  • 2012-08-11
  • 1970-01-01
  • 2015-09-25
  • 1970-01-01
  • 2020-01-05
  • 1970-01-01
  • 2019-03-22
  • 2013-10-09
  • 1970-01-01
相关资源
最近更新 更多