如何获取Pandas列多索引名称作为列表 [英] How to get Pandas column multiindex names as a list

查看:180
本文介绍了如何获取Pandas列多索引名称作为列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下CSV数据:

id,gene,celltype,stem,stem,stem,bcell,bcell,tcell
id,gene,organs,bm,bm,fl,pt,pt,bm
134,foo,about_foo,20,10,11,23,22,79
222,bar,about_bar,17,13,55,12,13,88

我可以通过这种方式成功地总结它们:

And I can successfully summarize them this way:

import pandas as pd
df = pd.read_csv("http://dpaste.com/1X74TNP.txt",header=None,index_col=[1,2]).iloc[:, 1:]

df.columns = pd.MultiIndex.from_arrays(df.ix[:2].values)
df = df.ix[2:].astype(int)
df.index.names = ['cell', 'organ']
df = df.reset_index('organ', drop=True)

result = df.groupby(level=[0, 1], axis=1).mean()
result = result.stack().replace(np.nan, 0).unstack()
result = result.swaplevel(0,1, axis=1).sort_index(axis=1)

看起来像:

In [341]: result
Out[341]:
        bm               fl               pt
     bcell stem tcell bcell stem tcell bcell stem tcell
cell
foo      0   15    79     0   11     0  22.5    0     0
bar      0   15    88     0   55     0  12.5    0     0

我的问题是,如何从result获取第一级的列索引作为列表:

My question is, from result how can I get the column index of the first level as list:

['bm','fl','pt']

推荐答案

result.columns返回具有级别属性的pandas.core.index.MultiIndex.

result.columns returns a pandas.core.index.MultiIndex which has a levels attribute.

list(result.columns.levels[0])

返回

['bm', 'fl', 'pt']

这篇关于如何获取Pandas列多索引名称作为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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