2016-08-20 130 views
0

我用一个大熊猫数据帧的pandas.pivot_table功能和我的输出看起来像这样的东西呈三角:熊猫透视表格式的列名

    Winners     Runnerup    
     year  2016 2015 2014 2016 2015 2014 
Country Sport        
india badminton        
india wrestling 

我真正需要的是像下面

Country Sport Winners_2016 Winners_2015 Winners_2014 Runnerup_2016 Runnerup_2015 Runnerup_2014 
india badminton 1 1 1 1 1 1 
india wrestling 1 0 1 0 1 0 
一些事情

我有很多专栏和年份,所以我将无法手动编辑它们,所以任何人都可以请告诉我如何做到这一点?

回答

3

您也可以使用列表理解:

df.columns = ['_'.join(col) for col in df.columns] 
print (df) 
        Winners_2016 Winners_2015 Winners_2014 Runnerup_2016 \ 
Country Sport                 
india badminton    1    1    1    1 
     wrestling    1    1    1    1 

        Runnerup_2015 Runnerup_2014 
Country Sport          
india badminton    1    1 
     wrestling    1    1 

与转换columnsto_series然后另一种解决方案调用join

df.columns = df.columns.to_series().str.join('_') 
print (df) 
        Winners_2016 Winners_2015 Winners_2014 Runnerup_2016 \ 
Country Sport                 
india badminton    1    1    1    1 
     wrestling    1    1    1    1 

        Runnerup_2015 Runnerup_2014 
Country Sport          
india badminton    1    1 
     wrestling    1    1 

我正要定时真正感兴趣的是:

In [45]: %timeit ['_'.join(col) for col in df.columns] 
The slowest run took 7.82 times longer than the fastest. This could mean that an intermediate result is being cached. 
100000 loops, best of 3: 4.05 µs per loop 

In [44]: %timeit ['{}_{}'.format(x,y) for x,y in zip(df.columns.get_level_values(0),df.columns.get_level_values(1))] 
The slowest run took 4.56 times longer than the fastest. This could mean that an intermediate result is being cached. 
10000 loops, best of 3: 131 µs per loop 

In [46]: %timeit df.columns.to_series().str.join('_') 
The slowest run took 4.31 times longer than the fastest. This could mean that an intermediate result is being cached. 
1000 loops, best of 3: 452 µs per loop 
+0

真的很感兴趣 - 第一个列表的理解速度快了30倍。 – jezrael

+0

是的,这是非常有用的,因为我正在处理更大的数据集。谢谢! –

1

试试这个:

df.columns=['{}_{}'.format(x,y) for x,y in zip(df.columns.get_level_values(0),df.columns.get_level_values(1))] 

get_level_values是你需要得到的只是得到的多指标水平的一个东西。

备注:您可能会尝试使用这些数据。我真的很讨厌大熊猫multiIndex,但它长在我身上。