0

I want to import a python file called feature.py and call the functions in it, so I did the 'from feature import *'.

from feature import *

In the feature.py, I import pandas as pd and define the functions that I would like to call in the main python file.

import pandas as pd

# time features
def add_time_features(df):
    df["date"] = pd.to_datetime(data.Timestamp, unit='s').dt.date
    df["month"] = pd.to_datetime(data.Timestamp, unit='s').dt.month
    df["weekday"] = pd.to_datetime(data.Timestamp, unit='s').dt.weekday_name
    df["hour"] = pd.to_datetime(data.Timestamp, unit='s').dt.hour

However, when I run the main python program and call the function I got the error message said pd is not defined. enter image description here

I thought I did define pd by using "import pandas as pd" in both main file and the feature.py. Bu it does not work. So what is the correct method to do this?

NVRM
  • 11,480
  • 1
  • 88
  • 87
user10262232
  • 71
  • 1
  • 9
  • Please Check Here , May be help you ! https://stackoverflow.com/questions/14295680/unable-to-import-a-module-that-is-definitely-installed – Rahul Kr Daman Dec 09 '19 at 05:43
  • Thanks for your suggestion. However, this is different. I don't have an error when importing, but the program seems will not run the import statement. – user10262232 Dec 09 '19 at 05:48

1 Answers1

0

When you import code from another file in the form “import filename” then it doesn’t do the same thing as when you extract functions/classes from a file in the form “from filename import *”.

The code you’ve shown appears to be taking the functions from the file you’re importing without actually running the import statement. A simple fix should be to put an “import pandas as pd” statement in the main file.

Essentially the functions you have imported act in a similar/identical way to the functions written in the main file so likely obey the same rules and have access to the same import statements.

Does this help?