首页 > 解决方案 > 如何将函数调用到文件中

问题描述

我正在尝试导入一个函数,该函数在另一个文件夹中具有此结构的文件:

Data_Analytics
|---Src
|    ---__init.py__
|    ---DEA_functions.py
|    ---importing_modules.py
|---Data Exploratory Analysis
|    ----File.ipynb

所以,从 File.ipynb(从现在开始我在笔记本上工作)我想调用我在文件 DEA_functions.py 中的一个函数。为此,我输入:

import sys
sys.path.insert(1, "../")
from Src.Importing_modules import *
import Src.DEA_functions as DEA

导入过程中没有错误,但是当我想调用该函数时出现此错误:

AttributeError: module 'Src.DEA_functions' has no attribute 'getIndexes'
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-29-534dff78ff93> in <module>
      4 
      5 #There is a negative value that we want to delete
----> 6 DEA.getIndexes(df,df['Y3'].min())
      7 df['Y3'].min()
      8 df['Y3'].iloc[14289]=0

AttributeError: module 'Src.DEA_functions' has no attribute 'getIndexes'e

并且函数在文件中定义,这样:

def getIndexes(dfObj, value):
''' Get index positions of value in dataframe i.e. dfObj.'''
listOfPos = list()
# Get bool dataframe with True at positions where the given value exists
result = dfObj.isin([value])
# Get list of columns that contains the value
seriesObj = result.any()
columnNames = list(seriesObj[seriesObj == True].index)
# Iterate over list of columns and fetch the rows indexes where value exists
for col in columnNames:
    rows = list(result[col][result[col] == True].index)
    for row in rows:
        listOfPos.append((row, col))
# Return a list of tuples indicating the positions of value in the dataframe
return listOfPos

我希望我说清楚了,但如果不是毫不犹豫地质疑你需要的任何东西。我只想使用我在文件 DEA_functions.py 中定义的函数到我的 File.ipynb

谢谢!

标签: pythonfunctiondirectory-structure

解决方案


我发现了错误,我将 DEA 指定为调用我的函数的短名称。看起来我必须使用小写字母。所以:

import Src.DEA_funct as dea

推荐阅读