Python ImportError:无法导入名称 __init__.py

2024-05-18

我收到此错误:

ImportError: cannot import name 'life_table' from 'cdc_life_tables' (C:\Users\tony\OneDrive\Documents\Retirement\retirement-mc-master\cdc_life_tables\__init__.py)

当我尝试运行这个时(retirement_mc.py):

from cdc_life_tables import life_table

__init__.py看起来像这样

#!/usr/bin/env python
from cdc_life_tables import *

and cdc_life_tables.py包含life_table看起来像这样:

def life_table(state_abbrev, demographic_group):
  
    state_abbrev = state_abbrev.upper()

    try:
        state = abbrev2name[state_abbrev]
    except KeyError:
        raise ValueError('"{}" not a state abbreviation.'.format(state_abbrev))

    state = state.lower().replace(' ', '_')


    try:
        demographic_group = demographic_group.lower()
        if len(demographic_group) > 2:
           demographic_group = groups_long2short[demographic_group]
    except KeyError:
        raise ValueError('"{}" not a valid .'.format(demographic_group))
        
    s = '{}{}_{}.csv'.format(lt_dir, state, demographic_group)

    if os.path.exists(s):
        df = pd.read_csv(s)
    else:
        raise ValueError('{} not a demographic group for {}.'.format(demographic_group, state_abbrev))

    return df['qx']
       
if __name__ == '__main__':
    q = life_table('PA', 'wf')

我正在使用 Spyder (Python 3.7)


有了这一行:

from cdc_life_tables import *

您的包裹正在​​尝试import * from itself。你需要import *来自cdc_life_tables 子模块当前包的,最容易通过相对导入完成:

from .cdc_life_tables import *
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python ImportError:无法导入名称 __init__.py 的相关文章