当我导入模块时,scipy.stats丢失 [英] scipy.stats is lost when I import my module

查看:31
本文介绍了当我导入模块时,scipy.stats丢失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅当我通过Linux命令行(即Linux的Windows子系统)运行代码时,才会出现该问题。在Windows上通过Conda环境运行时不会发生这种情况。在这两种情况下,都正确安装了scipy

我已经创建了一个函数来执行两个数据帧df_1df_2中行中的值的线性回归。它们的列名与字典data_dict的键相同。

from scipy.stats import linregress
import numpy as np

def foo(df_1, df_2, data_dict):
    for index, row in df_2.iterrows():
        x = []
        for d in data_dict:
            x.append(row[d])
        x = np.array(x)
    for index, row in df_1.iterrows():
        y = []
        for d in data_dict:
            y.append(row[d])
        y = np.array(y)
        s, i, r, p, se = linregress(x, y)

只要我在编写它的脚本中运行它,就可以很好地运行它,但是只要我将它导入到另一个脚本‘bar’中并尝试运行它,我就得到错误AttributeError: module 'scipy' has no attribute 'stats',并且回溯是指实际使用linregress的行,而不是导入行。

我已尝试通过其他方式导入,即

from scipy import stats

以及在线性回归操作前直接导入,即

from scipy.stats import linregress
s, i, r, p, se = linregress(x, y)

最后,我尝试查看导入到‘bar’的其他模块是否干扰scipy.stats,但情况并非如此。

你知道为什么python‘忘记’scipy.stats吗?

我还尝试通过在调用foo之前编写在‘bar’中导入的所有模块的列表来检查scipy.stats是否已导入;

with open('modules_on_import.txt', 'a') as f:
    for s in sys.modules:
        f.write(f"{s}
")
f.close()

和scipy.stats可在MODULES_ON_port.txt

中找到

更多详细信息:

  1. 我没有在虚拟环境中运行,echo $VIRTUAL_ENV不返回任何内容。
  2. 所有操作都通过命令行运行,即直接在Bash中运行。在本例中,我只需输入python3 bar.py
  3. 通过命令行使用pip安装的所有模块-即pip install scipy
  4. 不确定是否重要,但我正在vim中编辑。

bar.py的(简化)示例。

from psd_processing import process_psd # function to make df_2 and data_dict
from uptake_processing import process_uptake # function to make df_1
from foo_test import foo

project = '0020'
loading_df = process_uptake(project, 'co2', 298) # this works
param_df, data_dict = process_psd(project, 'n2', 'V') # this works
correlation_df = foo(loading_df, param_df, data_dict) # this breaks on linregress in foo.py

不是scipy的安装方法。我卸载并重新安装了pip3以确保。

但是,当我通过Spyder IDE运行代码时,它工作了! 一些相关信息;

  1. 我最初在Windows10x86_64上通过Ubuntu 20.04.3 LTS运行代码。我的Python安装在Ubuntu上的/usr中。
  2. 在Spyder中运行时,代码直接在Windows上运行。Python安装在C:Users<user>Anaconda3中。

如何通过命令行使此代码正常运行?

推荐答案

如问题中所述,此代码在Windows中的Conda venv上运行,但不能在直接安装在Ubuntu WSL上的python3上运行。由于我的首选是使用Linux命令行,因此我执行了以下解决方法;

  1. Install Anaconda on the Ubuntu WSL
  2. 创建并激活虚拟环境。
  3. 通过conda install <pkg>在虚拟环境中安装所需的包。
  4. 在新的虚拟环境中运行所有内容。

这篇关于当我导入模块时,scipy.stats丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆