python – 如何将Pandas列多索引名称作为列表
发布时间:2021-01-11 06:55:26 所属栏目:Python 来源:互联网
导读:我有以下CSV数据: id,gene,celltype,stem,stem,stem,bcell,bcell,tcellid,gene,organs,bm,bm,fl,pt,pt,bm134,foo,about_foo,20,10,11,23,22,79222,bar,about_bar,17,13,55,12,13,88 我可以用这种方式成功地总结出来: import pandas as
我有以下CSV数据: id,gene,celltype,stem,bcell,tcell id,organs,bm,fl,pt,bm 134,foo,about_foo,20,10,11,23,22,79 222,bar,about_bar,17,13,55,12,88 我可以用这种方式成功地总结出来: 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 我的问题是,从结果如何获得第一级列列索引作为列表: ['bm','fl','pt'] 解决方法result.columns返回一个pandas.core.index.MultiIndex,它有一个levels属性.list(result.columns.levels[0]) 回报 ['bm','pt'] (编辑:莱芜站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 版本控制 – Mercurial日志界面
- python – Pandas:重新采样后计算唯一值
- python – 替换numpy数组中的元素,避免循环
- 在Django中使用python-social-auth和电子邮件注册复制电子邮
- python – OPENCV:Calibratecamera 2重投影错误和自定义计
- python – Sublime Text 3 API:从文件获取所有文本
- python – 如何提高INSERT语句的性能?
- python – Pandas列重新格式化
- 【Python】python文件打开方式详解——a、a+、r+、w+区别
- python – 有效地将numpy数组与元素进行比较