2015-11-23 123 views
1

我想轉換foll。據幀:從熊貓數據框中提取多行並轉換爲列

index YR BIOM RWT site 
0  0 2008 0.53 0.20 1 
1  1 2009 3.23 1.18 1 
2  2 2010 11.51 3.94 1 
3  3 2011 18.14 5.82 1 
4  4 2012 22.88 6.73 1 
5  5 2013 26.65 7.20 1 
6  0 2008 0.39 0.15 10 
7  1 2009 2.43 0.90 10 
8  2 2010 8.95 3.09 10 
9  3 2011 16.63 5.38 10 
10  4 2012 24.36 7.23 10 
11  5 2013 29.72 8.10 10 

我想提取BIOM值的2獨特site即1和10的YR 2008年和2013年,使我得到這樣的:

index BIOM_2008  BIOM_2013 site 
0   0.53   26.65  1 
1   26.65  29.72  10 

這是什麼我在做:

lst_yrs = [2008, 2013] 
sub_df = df[['YR', 'BIOM', 'site']] 

for yr in lst_yrs: 
    sub_df['BIOM'+str(yr)] = sub_df.loc['YR' == yr] 

不知道如何獲得for循環的權利。

+0

看看這個: http://stackoverflow.com/questions/29941384/how-can-i-use-melt-to-reshape-a-pandas-dataframe-to-a-list-creating- an-index – toasteez

回答

1

我不確定你需要在這裏循環。你可以簡單地創建所需的數據的切片,設置索引,然後拆散如下:

import pandas as pd 

DF = pd.DataFrame({ 
'site' : [1, 1, 1, 1, 1, 1, 10, 10, 10], 
'BIOM' : [0.53, 3.23, 11.51, 18.14, 22.88, 26.65, 0.39, 2.43, 8.95], 
'YR' : ['2008', '2009', '2010', '2011', '2012', '2013', '2008', '2009', '2010'] 
        }) 

slice = DF[(DF['site'].isin([1, 10]) & DF['YR'].isin(['2008', '2013']))] 

result = slice.set_index(['site','YR']).unstack('YR') 

其中給出以下幾點:

 BIOM  
YR 2008 2013 
site    
1  0.53 26.65 
10 0.39 NaN 

在回答您的意見,扁平化層級列索引做到以下幾點:

result.columns = [' '.join(col).strip() for col in result.columns.values] 


    site BIOM 2008 BIOM 2013 
0  1  0.53  26.65 
1 10  0.39  NaN 

可能這是現在比你原來的想法循環更加複雜,但我認爲它使用的大熊貓功能更復雜的方式。

+0

謝謝@WoodyPride,這看起來不錯。如何將其轉換爲我需要的格式(如上面的問題)? – user308827

相關問題