pd not defined when importing custom functions locally - python

I have files with functions saved locally that I want to load. However, when I do this, its not picking up already loaded loaded packages such as pandas.
import pandas as pd
import numpy as np
x=pd.DataFrame({"a":[1,2,3]})
This function is saved locally to a test_function.py file...it isn't run in my jupter notebook directly.
# saved on file locally...
def multiply_values(data):
if data.__class__ == pd.DataFrame():
return(x.iloc[:,0]*2)
Load the function...
from test_function import *
multiply_values(x)
I then get
NameError: name 'pd' is not defined
Can someone explain to me how I should be handling this? How am I not importing this correctly?
I also updated the test_function.py file to have
import pandas as pd as the very first line & within the function itself.
I get this response:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-75-00666e9e2407> in <module>
1 xx = pd.DataFrame({'a':[0,23,234,3]})
2
----> 3 multiply_values(xx)
~/Downloads/testfunc.py in multiply_values(data)
1 import pandas as pd
2
----> 3
4 def multiply_values(data):
5 import pandas as pd
NameError: name 'pd' is not defined

Related

How to resolve the ImportError: cannot import name 'DesicionTreeClassifier' from 'sklearn.tree' in python?

Hello there,
I am new to python and I was trying out a project on jupyter notebook when I encountered an error which I couldn't resolve. I'd really appreciate some help.
This is my code:
import pandas as pd
from sklearn.tree import DesicionTreeClassifier
music_data = pd.read_csv(r'C:\python\python382\music.csv')
X=music_data.drop(columns=['genre'])
y=music_data['genre']
model=DesicionTreeClassifier()
model.fit(X,y)
music_data
And i got the output as :
ImportError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_2540/2462038274.py in <module>
1 import pandas as pd
----> 2 from sklearn.tree import DesicionTreeClassifier #using desicion tree algo here to make model[we import DesicionTree module from tree module which is imported from sklearn library]
3 music_data = pd.read_csv(r'C:\python\python382\music.csv')
4
5 ##Cleaning and segregating data
ImportError: cannot import name 'DesicionTreeClassifier' from 'sklearn.tree' (C:\python\python382\lib\site-packages\sklearn\tree\__init__.py)
Thank you.
You have missspelled the fumction name DesicionTreeClassifier is in reality DecisionTreeClassifier

How can I run a script after importing it?

Problem
I would like to import a script containing many functions and then run them, so that I can use the function. I may have misunderstood the purpose of import. I am working in Jupyter.
Reprex
#Create the script in a local folder
%%writefile test.py
c = 500
def addup(a,b,c):
return a*b + (c)
#import the file and use it
import test
addup(1,5,c)
#Error message
---------------------------------------------------------------------------
# NameError Traceback (most recent call last)
# <ipython-input-1-71cb0c70c39d> in <module>
# 1 import test
# ----> 2 addup(1,5,c)
# NameError: name 'addup' is not defined
Any help appreciated.
You have not called the function! You need a dot . to call a function from a module.
This is the correct syntax:
import test
result = test.addup(1,5,c)
Import a specific function:
from test import addup
addup(1,5,c)
Importing all of the module's functions:
from test import *
addup(1,5,c) # this way you can use any function from test.py without the need to put a dot

Import module has no attribute

I'm using Python since few days and I'm trying to learn as much as possible from it. I'm using Jupyter notebook as well. I made a python file fibo.py where I code a function fib and I saved it. In the same folder I try to import that module and use the function fib
import pandas as pd
import numpy as np
import fibo
result = fibo.fib(10)
but I get the following error message :
AttributeError: module 'fibo' has no attribute 'fib'
Could you please give me some suggestions where the problem should be? Thank you in advance.
This is the code for fibo.py
# Fibonacci numbers module\n",
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()
The error I get is here:
AttributeError Traceback (most recent call last)
<ipython-input-1-73202afd3146> in <module>
3
4 import fibo
----> 5 result = fibo.fib(10)
AttributeError: module 'fibo' has no attribute 'fib'
I tried also
from fibo import fib
And I get the following:
ImportError Traceback (most recent call last)
<ipython-input-2-b2d78eaf1dcb> in <module>
4 import fibo
5 #result = fibo.fib(10)
----> 6 from fibo import fib
ImportError: cannot import name 'fib' from 'fibo' (C:\Users\my_folder\Documents\JupyterWork\fibo.py)
Save the file as .py using any text editor other than jupyter notebook.
Because jupyter notebook file are stored in JSON format.

Using one module inside another in Python

I am trying to make some code a bit more modular in Python and am running into one issue which I'm sure is straight forward but I can't seem to see what the problem is.
Suppose I have a script, say MyScript.py:
import pandas as pd
import myFunction as mF
data_frame = mF.data_imp()
print(data_frame)
where myFunction.py contains the following:
def data_imp():
return pd.read_table('myFile.txt', header = None, names = ['column'])
Running MyScript.py in the command line yields the following error:
Traceback (most recent call last):
File "MyScript.py", line 5, in <module>
data_frame = mF.data_imp()
File "/Users/tomack/Documents/python/StackQpd/myFunction.py", line 2, in data_imp
return pd.read_table('myFile.txt', header = None, names = ['column'])
NameError: name 'pd' is not defined
You need to import pandas in your function or script myFunction:
def data_imp():
import pandas as pd
return pd.read_table('myFile.txt', header = None, names = ['column'])
Answers here are right, because your module indeed lacks myFunction import.
If stated more broad this question can also contain following: in case of circular import the only 2 remedies are:
import pandas as pd , but not from pandas import something
Use imports right there in functions you need in-placd

Python: Function: not recognizing dependencies

I am quite new to writing modules in Python.
I use Python 3.5
I have a script called describeToolbox.py that contain functions that I would like to be able to call, like this one:
#describeToolbox.py
import shelve
def getRawData(prefix):
shelfFile = shelve.open('data'+prefix)
df = shelfFile['data'+prefix]
shelfFile.close()
return df
This is meant to retrieve a dataFrame from a shelve file
In my console now, I write the following statements:
In [7]:import shelve
import describeToolbox as TB
In [8]:TB.getRawData('Myprefix')
Out [8]:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-9-67160af666cc> in <module>()
----> 1 TB.getRawData('Myprefix')
C:\Users\Math\Documents\Docs\Commos\Notebooks\describeToolbox.py in getRawData(prefix)
1 def getRawData(prefix):
----> 2 shelfFile = shelve.open('data'+prefix)
3 df = shelfFile['data'+prefix]
4 shelfFile.close()
5 return df
NameError: name 'shelve' is not defined
It gives me an error message saying that the module 'shelve', the dependency, is not defined.
Basically I dont know where is the correct place to import all the dependencies so that my function can load them when I want to import it.
I would like to write a depository of functions I use often in one module and call them when needed.
Thank you for your help!

Categories

Resources