本文介绍了重新排列Pandas数据透视表中的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用pivot_table方法创建的熊猫数据框.其结构如下:

I have a pandas dataframe created using the pivot_table method. It is structured as follows:

import numpy as np
import pandas 

datadict = {
 ('Imps', '10day avg'): {'All': '17,617,872', 'Crossnet': np.nan, 'N/A': '17,617,872'},
 ('Imps', '30day avg'): {'All': '17,302,111', 'Crossnet': '110','N/A': '18,212,742'},
 ('Imps', '3day avg'): {'All': '8,029,438', 'Crossnet': '116', 'N/A': '8,430,904'},
 ('Imps', 'All'): {'All': '14,156,666', 'Crossnet': '113', 'N/A': '14,644,823'},
 ('Spend', '10day avg'): {'All': '$439', 'Crossnet': np.nan, 'N/A': '$439'},
 ('Spend', '30day avg'): {'All': '$468', 'Crossnet': '$0', 'N/A': '$492'},
 ('Spend', '3day avg'): {'All': '$209', 'Crossnet': '$0', 'N/A': '$219'},
 ('Spend', 'All'): {'All': '$368', 'Crossnet': '$0', 'N/A': '$381'}
}
df = pandas.DataFrame.from_dict(datadict)
df.columns = pandas.MultiIndex.from_tuples(df.columns)

我尝试使用以下两种方法以新的顺序对支出"和展示"下的嵌套列进行重新排序,但是即使没有抛出错误,该顺序也保持不变:

I tried to reorder the nested columns under 'Spend' and 'Imps' in a new order using both of the below methods, however the order remains unchanged despite no errors being thrown:

df['Spend']=df['Spend'].reindex_axis(['3day avg','10day avg','30day avg','All'],axis=1)
df['Spend']=df['Spend'][['3day avg','10day avg','30day avg','All']]

推荐答案

一种方法是通过以下方式创建MultiIndex并重新索引:

One way is to create the MultiIndex and reindex by that:

In [11]: mi = pd.MultiIndex.from_product([['Imps', 'Spend'], ['3day avg','10day avg','30day avg','All']])

In [12]: df.reindex_axis(mi, 1)
Out[12]: 
               Imps                                        Spend                          
           3day avg   10day avg   30day avg         All 3day avg 10day avg 30day avg   All
All       8,029,438  17,617,872  17,302,111  14,156,666     $209      $439      $468  $368
Crossnet        116         NaN         110         113       $0       NaN        $0    $0
N/A       8,430,904  17,617,872  18,212,742  14,644,823     $219      $439      $492  $381

注意:MultiIndex.from_product是0.13中的新功能,如果您使用的熊猫年龄大于使用pd.MultiIndex.from_tuples(list(itertools.product(..)))的熊猫.

Note: MultiIndex.from_product is new in 0.13, if you're using a pandas older than that use pd.MultiIndex.from_tuples(list(itertools.product(..))).

这篇关于重新排列Pandas数据透视表中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 09:54