如何将数据帧从 Pandas 的一个模块导入到另一个模块?

发布于 2025-01-09 19:56:19 字数 957 浏览 1 评论 0原文

我想重用另一个模块中数据框中的一些列。

我想要类似

file1.py

A   B
25  Hello
30  How are you

file2.py

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

我尝试这样做,但它不起作用。

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

输出

    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

输出

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

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'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小姐丶请自重 2025-01-16 19:56:19

其实这看起来不错。如果您尝试以下操作

# file1.py          
def foo():
    print("foo")

# file2.py 
from file1 import foo

foo()

,然后在 file1.pyfile2.py 旁边的文件夹中运行 python file2.py,程序实际上应该打印foo

但这仅在您在 file1.pyfile2.py 所在的文件夹中执行 python 时才有效。

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.

围归者 2025-01-16 19:56:19

文件1.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

文件2.py

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

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())
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文