250527 Jupyter lab “import matplotlib” 报错

最近找到一个传感器数据集想看看里面的数据大致的情况,以前也用过Jupyter,因为可以一段一段运行代码显示结果,对于观察数据来说感觉很方便,所以就想在虚拟机的Ubuntu上安装一个试试。

安装倒是没什么好说的,但是装好之后,在import module的时候就出错了。
一共就三行

1
2
3
4
5
import pandas as pd

import numpy as np

import matplotlib.pyplot as plt 

首先是因为没有安装pandas和numpy报错,于是找了下怎么在Jupyter的cell里运行pip安装这俩module。
等安装好之后,第三行import又报错了

1
2
3
4
5
6
7
A module that was compiled using NumPy 1.x cannot be run in

NumPy 2.2.6 as it may crash. To support both 1.x and 2.x

versions of NumPy, modules must be compiled with NumPy 2.0.

Some module may need to rebuild instead e.g. with 'pybind11>=2.12'.

网上搜了会也没看到有什么解法,于是死马当活马医丢给Gemini问问是啥情况。Gemini分析可能是Jupyter kernel的Python环境问题,给的一个看起来靠谱一些的解决方案是给Jupyter创建个新的干净的虚拟环境。不过在执行下面的步骤之前我先把之前安装的Juypter lab卸载了。

Create a New, Clean Environment (Recommended)

This is often the cleanest way to avoid these conflicts.

  1. Open your terminal.
  2. Create a virtual environment:
    • Using venv (comes with Python 3):
      1
      2
      python3 -m venv a_path  # Choose a path for your environment
      source a_path/bin/activate # Activate it (use .\a_path\Scripts\activate on Windows)
    • Using conda (if you have Anaconda/Miniconda):
      1
      2
      conda create -n a_path python=3.9 # Or your preferred Python version
      conda activate a_path
  3. Install necessary packages within the activated environment:
    1
    pip install numpy pandas matplotlib jupyterlab ipykernel
  4. Create a Jupyter kernel for this new environment:
    1
    python -m ipykernel install --user --name=venv --display-name "jupyter_venv"
  5. Start Jupyter Lab.

这之后在Jupyter lab的新标签页的Notebook下面会出现刚刚创建的环境jupyter_venv,点击这个创建notebook就没问题了。
7c9070f2078cb9ab355b1757ceb4745b.png