简体   繁体   English

pandas从csv文件中读取MultiIndex数据

[英]pandas read in MultiIndex data from csv file

I have a MultiIndex csv file which I would like to read in. 我有一个MultiIndex csv文件,我想阅读。

The data is saved in the csv file as follows: 数据保存在csv文件中,如下所示:

import pandas as pd
import numpy as np

dfcsv = pd.read_csv("/FilePath/MultiIndex_Example.csv")
dfcsv

Which essentially leads to a data frame below: 这实际上导致了以下数据框:

在此输入图像描述

Python Dataframe construction below: (easy reconstruction) Python Dataframe构造如下:( 轻松重建)

d = {'Country': ['City', 'PostCode','Day1','Day2','Day3'], 'UK': ['London', '123',47,42,40],'USA': ['New York', '456',31,22,58]}
dfstd = pd.DataFrame(data=d)

However, when I read in the data I need the 1st column to act as the multiIndex. 但是,当我读入数据时,我需要第1列作为multiIndex。 Essentially creating a data frame as below: 基本上创建一个数据框如下:

arrays = [['UK','USA'],['London','New York'],['123','456']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['Country', 'City','Postcode'])
df = pd.DataFrame(np.random.randn(3, 2), index=['Day1', 'Day2', 'Day3'], columns=index)
df.columns 

在此输入图像描述

I was wondering if there is a simple way of achieving this via pd.read_csv or a pd.MultIndex construction ? 我想知道是否有一种通过pd.read_csv或pd.MultIndex构造实现这一目标的简单方法?

FYI I tried the below but couldn't get it working Load CSV to Pandas MultiIndex DataFrame 仅供参考我尝试了以下但无法使其工作将 CSV加载到Pandas MultiIndex DataFrame

I think the following is what you need: 我认为您需要以下内容:

dfcsv = pd.read_csv("/FilePath/MultiIndex_Example.csv", index_col=[0], header=[0,1,2])

Here, index_col will take your first column which is 0 as index and header as 1st and 2nd row as header's which are 0,1,2 as its 0-indexed 在这里, index_col就会把你的第一列是0的指数和头作为第一和第二行作为标题的这是0,1,20索引

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

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