【Python】import pandas时,报错 pandas Missing required dependencies ['numpy'] 原因分析
結論:在需要 import pandas 時,同級目錄下不要有 unittest.py同名文件,否則,會與pandas自帶的unittest沖突,導致 import pandas 失敗。
錯誤使用場景復現
建立了一個 testpandas.py,同時,在同級目錄下建立了一個 unittest.py。
在 testpandas.py 中 import pandas, 運行發現報錯。
報錯信息
Traceback (most recent call last):File "C:\Python27\lib\site-packages\pandas\__init__.py", line 13, in <module>__import__(dependency)File "C:\Python27\lib\site-packages\numpy\__init__.py", line 187, in <module>from .testing import TesterFile "C:\Python27\lib\site-packages\numpy\testing\__init__.py", line 10, in <module>from unittest import TestCase ImportError: cannot import name TestCase Traceback (most recent call last):File "C:/Users/Bug/PycharmProjects/md-jobs-latest/app/mdjob/testpandas.py", line 8, in <module>import pandasFile "C:\Python27\lib\site-packages\pandas\__init__.py", line 20, in <module>"Missing required dependencies {0}".format(missing_dependencies)) ImportError: Missing required dependencies ['numpy']原因分析
根據報錯,查看C:\Python27\lib\site-packages\numpy\testing\__init__.py源碼,如下:
"""Common test support for all numpy test scripts.This single module should provide all the common functionality for numpy tests in a single location, so that test scripts can just import it and work right away.""" from __future__ import division, absolute_import, print_functionfrom unittest import TestCasefrom ._private.utils import * from ._private import decorators as dec from ._private.nosetester import (run_module_suite, NoseTester as Tester)__all__ = _private.utils.__all__ + ['TestCase', 'run_module_suite']from numpy._pytesttester import PytestTester test = PytestTester(__name__) del PytestTester可以看到,第 10 行的from unittest import TestCase與上圖testpandas.py同級目錄下的unittest(自己創建的)產生同名沖突。
也就是說,在unittest中找不到TestCase。也可以理解為,自己創建的unittest從名稱上污染了官方的unittest,錯誤的引用了自己建的unittest,所以報錯。
解決方式
在需要 import pandas 時,同級目錄下不要有 unittest.py的同名文件,否則,會與pandas自帶的unittest沖突,導致 import pandas 失敗。
拓展閱讀:from future import absolute_import 的作用
關于from __future__ import absolute_import的作用:
直觀地看就是說”加入絕對引入這個新特性”。說到絕對引入,當然就會想到相對引入。
那么什么是相對引入呢?比如說,你的包結構是這樣的:
如果你在main.py中寫import string,那么在Python 2.4或之前, Python會先查找當前目錄下有沒有string.py, 若找到了,則引入該模塊,然后你在main.py中可以直接用string了。如果你是真的想用同目錄下的string.py那就好,但是如果你是想用系統自帶的標準string.py呢?那其實沒有什么好的簡潔的方式可以忽略掉同目錄的string.py而引入系統自帶的標準string.py。這時候你就需要from __future__ import absolute_import了。這樣,你就可以用import string來引入系統的標準string.py, 而用from pkg import string來引入當前目錄下的string.py了
總結
以上是生活随笔為你收集整理的【Python】import pandas时,报错 pandas Missing required dependencies ['numpy'] 原因分析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【阿里架构设计思想】一线互联网系统的核心
- 下一篇: 【Python】import xxx 文