【问题标题】:Excel to Pandas with a multi-level index producing NaNExcel to Pandas 具有产生 NaN 的多级索引
【发布时间】:2019-04-27 02:37:12
【问题描述】:

我正在使用这个数据集:

https://www.ons.gov.uk/employmentandlabourmarket/peopleinwork/employmentandemployeetypes/datasets/commutingtoworkbygenderukcountryandregion

这样加载:

commuting_data_xls = pd.ExcelFile(commuting_data_filename)
commuting_data_sheets = commuting_data_front['Table description '].dropna()
commuting_data_1 = pd.read_excel(commuting_data_xls, '1', header=4, usecols=range(1,13))
commuting_data_1.dropna().dropna(axis=1)

生成的分层索引仅获取指定所有索引列的行。

如何更正此问题并命名索引列?

【问题讨论】:

    标签: python python-3.x multi-index


    【解决方案1】:

    尝试以下步骤:

    1. 使用 pd.read_excel() 打开,只需要您想要的工作表和范围。

      commuting_data_xls = pd.read_excel("commutingdata.xlsx",'1', header=4, usecols=range(1,13))

    2. 重置多索引名称。

      commuting_data_xls.index.names = ['Gender', 'Work_Region', 'Region']

    重置索引,然后限制行以消除总数,我假设您希望它们消失?如果不只是删除 iloc 步骤。

    commuting_data_xls = commuting_data_xls.reset_index().iloc[0:28]
    

    删除“Work_Region”列,因为这似乎是多余的。

    commuting_data_xls = commuting_data_xls.loc[:,commuting_data_xls.columns != 'Work_Region']
    

    填写性别栏以替换 NaN

    commuting_data_xls['Gender'].fillna(method='ffill', inpldace=True)
    

    如果适合您的目的,请重置索引。

    commuting_data_xls.set_index('Gender', 'Region')
    

    【讨论】:

    • 那行得通,也教会了我一些东西。抱歉耽搁了,刚放假回来。
    猜你喜欢
    • 1970-01-01
    • 2017-09-06
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 1970-01-01
    • 2017-12-31
    • 1970-01-01
    • 2014-11-18
    相关资源
    最近更新 更多