【发布时间】:2022-01-09 05:20:54
【问题描述】:
只有当我通过 Linux 命令行(即 Linux 的 Windows 子系统)运行代码时才会出现问题。在 Windows 上通过 conda 环境运行时不会发生这种情况。在这两种情况下,scipy 都已正确安装。
我创建了一个函数来对来自两个数据框 df_1 和 df_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
以及在 linregress 操作之前直接导入,即
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}\n")
f.close()
和 scipy.stats 可以在 modules_on_import.txt 中找到
更多细节:
- 我没有在虚拟环境中运行,
echo $VIRTUAL_ENV没有返回任何内容。 - 一切都通过命令行运行,即直接在 Bash 中运行。在这种情况下,我只需输入
python3 bar.py。 - 通过命令行使用 pip 安装的所有模块 - 即
pip install scipy - 不确定是否重要,但我正在
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 运行代码时,它可以工作! 一些相关信息;
- 我最初是通过 Windows 10 x86_64 上的 Ubuntu 20.04.3 LTS 运行代码。我的 Python 安装在 Ubuntu 上的
/usr中。 - 在 Spyder 中运行时,代码直接在 Windows 上运行。 python安装在
C:\Users\<user>\Anaconda3。
如何让这段代码通过命令行正常运行?
【问题讨论】:
-
获得错误
AttributeError: module 'scipy' has no attribute 'stats'的一种方法是将scipy 导入为import scipy,然后尝试使用scipy.stats.linregress。stats子模块必须显式导入(例如import scipy.stats并使用scipy.stats.linregress,或from scipy import stats并使用stats.linregress),或者必须显式导入单个对象(例如from scipy.stats import linregress并使用linregress)。听起来您尝试了几种变体。您确定您展示的示例是产生该错误的示例吗? -
@WarrenWeckesser 是的,我已经尝试将 foo 导入到一个新脚本中,完全按照您在此处看到的那样编写。 wrt到import方法,就是the first thing i found,不过我一直都是专门导入linregress的。
-
你是使用anaconda还是venv来创建虚拟环境?听起来您正在使用不同的 python 环境运行两个不同的脚本。请说明您是如何设置环境、安装软件包和运行这两个脚本的。如果你展示一个实际的运行(即直接从你运行代码的地方复制/粘贴)而不是仅仅试图用文字来解释,这将有所帮助。
-
@Code-Apprentice 我在 bash 中运行所有东西,即
python3 foo.py。我还在 foo 和 bar 中打印了sys.executable和sys.prefix,并从两个脚本/usr/bin/python3和/usr得到相同的答案。将在原始帖子中添加更多信息。 -
@jjramsey 我已经更新了问题以反映这一点,但 scipy 安装似乎不是问题。这似乎与 WSL 有关。
标签: python scipy conda windows-subsystem-for-linux