Search code examples
pythonpandasdataframepython-importimporterror

How to import a dataframe from one module to another in Pandas?


I would like to reuse some columns from a dataframe which are in another module.

I want something like

file1.py

A   B
25  Hello
30  How are you

file2.py

A   B                 C
25  Hello            Hola
30  How are you      Como estas

I tried doing this, but it does not work.

file1.py

import pandas as pd
def cr():
    data = {'state': ['Ohio','Ohio','Ohio','Nevada','Nevada'],
            'year': [2000,2001,2002,2001,2002],
            'pop': [1.5,1.7,3.6,2.4,2.9]}
    df = pd.DataFrame(data)
    return df

output:

    state   year    pop
0   Ohio    2000    1.5
1   Ohio    2001    1.7
2   Ohio    2002    3.6
3   Nevada  2001    2.4
4   Nevada  2002    2.9

file2.py

from file1 import cr

output

ImportError: cannot import name 'cr' from 'file1'

Solution

  • file1.py

    import pandas as pd
    def cr():
        data = {'state': ['Ohio','Ohio','Ohio','Nevada','Nevada'],
                'year': [2000,2001,2002,2001,2002],
                'pop': [1.5,1.7,3.6,2.4,2.9]}    
        return data
    

    file2.py

        import file1
        import pandas as pd
        file1.cr()
        df = pd.DataFrame(file1.cr())