Home > OS >  How to import and use my own function from .py file in Python Pandas?
How to import and use my own function from .py file in Python Pandas?

Time:05-31

In Jupyter Notebook I created my own function in my_fk.py file like below:

import pandas as pd

def missing_val(df):

    df= pd.DataFrame(df.dtypes, columns=["type"])
    df["missing"] = pd.DataFrame(df.isna().any())
    df["sum_miss"] = pd.DataFrame(df.isna().sum())
    df["perc_miss"] = round((df.apply(pd.isna).mean()*100),2)
    
    return df

Then when I try to import and run my function using below code:

    import pandas as pd
    import numpy as np
    import my_fk as fk
df = pd.read_csv("my_data.csv")
    fk.missing_val(df)

I have error like below. Error suggests that in my my_fk.py file there is no pandas as pd, but there IS line with code "import pandas as pd". How can I import and use my own function from python file ?

NameError: name 'pd' is not defined

CodePudding user response:

Missing "as". Then place your pd.read_csv() after importing pandas, not before

import pandas as pd
import numpy as np
import my_fk as fk


df = pd.read_csv("my_data.csv")
fk.missing_val(df)
  • Related