'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 1:[1]
Actually that looks good. If you try the following
# file1.py
def foo():
print("foo")
# file2.py
from file1 import foo
foo()
and then run python file2.py in the folder next to file1.py and file2.py, the program should actually print foo.
But this only works, if you execute pythonin the folder where file1.py and file2.py are located.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Michael Kopp |
