pandas 从 csv 文件中读取 MultiIndex 数据 [英] pandas read in MultiIndex data from csv file

查看:56
本文介绍了 pandas 从 csv 文件中读取 MultiIndex 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我想读入的 MultiIndex csv 文件.

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

将pandas导入为pd将 numpy 导入为 npdfcsv = pd.read_csv("/FilePath/MultiIndex_Example.csv")文件格式

这基本上会导致下面的数据框:

Python Dataframe 构建如下: (简单重构)

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

<块引用>

但是,当我读入数据时,我需要第一列作为多索引.基本上创建一个数据框如下:

arrays = [['UK','USA'],['London','New York'],['123','456']]元组 = 列表(zip(*数组))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

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

仅供参考,我尝试了以下操作,但无法正常工作将 CSV 加载到 Pandas MultiIndex DataFrame

解决方案

我认为以下是您所需要的:

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

在这里,index_col 会将您的第一列 0 作为索引,将标题作为第一行和第二行作为标题,即 0,1,2 作为它的 0-indexed

I have a MultiIndex csv file which I would like to read in.

The data is saved in the csv file as follows:

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)

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 

I was wondering if there is a simple way of achieving this via pd.read_csv or a pd.MultIndex construction ?

FYI I tried the below but couldn't get it working Load CSV to 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

这篇关于 pandas 从 csv 文件中读取 MultiIndex 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆