将层次结构或多索引应用于 pandas 列 [英] apply hierarchy or multi-index to pandas columns

查看:35
本文介绍了将层次结构或多索引应用于 pandas 列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过很多关于如何分层排列数据框行索引的例子,但我试图对列做同样的事情并且不理解语法:

我正在从 csv 文件中读取内容,如下所示

df=pandas.read_csv("data.csv")

和 data.csv 包含以下内容:

rno,marktheory1,marklab1,marktheory2,marklab21、78、45、34、542、23、54、87、46

所以在[1]:df给

 rno mark1 lab1 mark2 lab20 1 78 45 34 541 2 23 54 87 46

我想要做的是向列添加分层索引甚至类似于标签的东西,使它们看起来像这样:

 Subject1 Subject2rno 标记 1 实验室 1 标记 2 实验室 20 1 78 45 34 541 2 23 54 87 46

解决方案

这里有一个快速修复的解决方案:

data = pd.read_csv('data.csv')>>>数组 = [['', 'Subject1', 'Subject1', 'Subject2', 'Subject2'], data.columns]>>>df = pd.DataFrame(data.values, columns=arrays)>>>打印文件主题 1 主题 2rno 标记 1 实验室 1 标记 2 实验室 20 1 78 45 34 541 2 23 54 87 46[2 行 x 5 列]

另一种方式来做同样的事情:

<预><代码>>>>data = pd.read_csv('data.csv')>>>data_pieces = [data.ix[:, [0]], data.ix[:, [1, 2]], data.ix[:, [3,4]]]>>>data = pd.concat(data_pieces,axis=1,keys=['','Subject1','Subject2'])>>>打印数据主题 1 主题 2rno 标记 1 实验室 1 标记 2 实验室 20 1 78 45 34 541 2 23 54 87 46[2 行 x 5 列]

I have seen lots of examples on how to arrange dataframe row indexes hierarchically, but I am trying to do the same for columns and am not understanding the syntax:

I am reading the contents from a csv file as follows

df=pandas.read_csv("data.csv")

and data.csv contains something like:

rno,marktheory1,marklab1,marktheory2,marklab2
1,78,45,34,54
2,23,54,87,46

so In[1]:df gives

   rno  mark1  lab1  mark2  lab2
0    1     78    45     34    54
1    2     23    54     87    46

What I would like to do is add a hierarchical index or even something akin to a tag to the columns, so that they looked something like this:

        Subject1     Subject2   
   rno  mark1  lab1  mark2  lab2
0    1     78    45     34    54
1    2     23    54     87    46

解决方案

Here is a quick-fix solution for you:

data = pd.read_csv('data.csv')
>>> arrays = [[ '', 'Subject1', 'Subject1', 'Subject2', 'Subject2'], data.columns]
>>> df = pd.DataFrame(data.values, columns=arrays)
>>> print df
        Subject1        Subject2      
   rno     mark1  lab1     mark2  lab2
0    1        78    45        34    54
1    2        23    54        87    46

[2 rows x 5 columns]

Just another way to do the same:

>>> data = pd.read_csv('data.csv')
>>> data_pieces = [data.ix[:, [0]], data.ix[:, [1, 2]], data.ix[:, [3,4]]]
>>> data = pd.concat(data_pieces, axis=1, keys=['','Subject1', 'Subject2'])
>>> print data
        Subject1        Subject2      
   rno     mark1  lab1     mark2  lab2
0    1        78    45        34    54
1    2        23    54        87    46

[2 rows x 5 columns]

这篇关于将层次结构或多索引应用于 pandas 列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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