简体   繁体   English

如何使用 pandas python 从 excel 读取 MultiIndex 组数据

[英]How to read MultiIndex group data from excel using pandas python

I am having data like below我有如下数据

在此处输入图像描述

I need to fetch day-wise data based on locations for each name.我需要根据每个名称的位置获取每日数据。

I know how to fetch data from excel if it is having single row header but I am not getting how to fetch data from mentioned excel format format.我知道如何从 excel 获取数据,如果它有单行 header 但我不知道如何从提到的 excel 格式格式获取数据。

could anyone help me to solve this so it will help me to do my further work.谁能帮我解决这个问题,这样可以帮助我做进一步的工作。

I want to achieve something like this.我想实现这样的目标。

import pandas as pd

df = pd.read_excel('test.xlsx', header=[0,1], index_col=[0], sheet_name='Sheet1')
print(df)

lst = []
for i in range(0, len(df['Location1'])):
    dict = {}
    dict["name"] = df['Name'][i]
    dict["location1_day1"] = df['Location1']['Day1'][i]
    dict["location1_day2"] = df['Location1']['Day2'][i]
    dict["location2_day1"] = df['Location2']['Day1'][i]
    dict["location2_day2"] = df['Location2']['Day2'][i]
    lst.append(dict)

print(lst)

expected output预计 output

Name = Rose, Location1_Day1 = 1, Location1_Day2 = 2, Location1_Day3 = 3,Location2_Day1 = 11, Location2_Day2 = 12, Location2_Day3 = 13,
Name = Jasmine, Location1_Day1 = 4, Location1_Day2 = 5, Location1_Day3 = 6,Location2_Day1 = 14, Location2_Day2 = 15, Location2_Day3 = 16
import pandas as pd
df = pd.read_excel('../test.xlsx', 
    header=[0,1], index_col=[0], sheet_name='Sheet1')

the header option allows you to specify a list of rows corresponding to the column names. header选项允许您指定与列名对应的行列表。 index_col allows you to specify the index column, and specifies that name does not have multiple-column keys. index_col允许您指定索引列,并指定该名称没有多列键。 the dataframe can be indexed like this: dataframe 可以这样索引:

df['Location 1']['Day2']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM