+-
python – pandas从csv文件中读取MultiIndex数据
我有一个MultiIndex csv文件,我想阅读.

数据保存在csv文件中,如下所示:

import pandas as pd
import numpy as np

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

这实际上导致了以下数据框:

enter image description here

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. 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 

enter image description here

我想知道是否有一种通过pd.read_csv或pd.MultIndex构造实现这一目标的简单方法?

仅供参考我尝试过以下但是无法正常工作
Load CSV to Pandas MultiIndex DataFrame

最佳答案
我认为您需要以下内容:

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

这里,index_col将第一列作为索引,第一列为第一行和第二行作为头部,其为0,1,2作为其0索引

点击查看更多相关文章

转载注明原文:python – pandas从csv文件中读取MultiIndex数据 - 乐贴网