2016-07-13 126 views
2

我需要一些幫助來構建數據。所以我有以下DataFrame(稱爲df): the original dataframe熊貓用舊的列名創建一個新的數據框

我想根據Mean_CArea,Mean_CPressure和Mean_Force將我的數據幀分組。但是,我得到了以下結果:

wrongresult

正如你可能會看到列名不0,1,2 NATIVE_RH,ANATOMICAL_RH和NON_ANATOMICAL_RH。有沒有辦法從原始數據框中獲取正確的列名稱?

這裏是我到目前爲止的代碼:

def function(self, df): 
    d = dict() 
    for head in df.columns.tolist(): 
     RH, j_mechanics = head 
     if j_mechanics not in d: 
      d[j_mechanics] = df[head] 
     else: 
      d[j_mechanics] = pd.concat([d[j_mechanics],df[head]], axis=1, ignore_index=True) 
    for df_name, df in sorted(d.items()): 
     print(df_name) 
     print(df.head()) 

提前非常感謝!

+0

您是否檢查過'groupby'函數? http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html – jbndlr

回答

2

IIUC您可以通過列(axis=1),並通過第一級使用swaplevelgroupbylevel=0):

df = pd.DataFrame({('B', 'a'): {0: 4, 1: 10}, ('B', 'b'): {0: 5, 1: 11}, ('B', 'c'): {0: 6, 1: 12}, ('A', 'a'): {0: 1, 1: 7}, ('A', 'c'): {0: 3, 1: 9}, ('A', 'b'): {0: 2, 1: 8}}) 

print (df) 
    A   B   
    a b c a b c 
0 1 2 3 4 5 6 
1 7 8 9 10 11 12 
df.columns = df.columns.swaplevel(0,1) 

for i, g in df.groupby(level=0, axis=1): 
    print (g) 
    a  
    A B 
0 1 4 
1 7 10 
    b  
    A B 
0 2 5 
1 8 11 
    c  
    A B 
0 3 6 
1 9 12 
+0

非常感謝!這正是我正在尋找的! – arnold

+0

@arnold如果你覺得這篇文章有用,你可以加入它。 – piRSquared

1

你想用xs

df.xs('Mean_CArea', axis=1, level=1) 

df.xs('Mean_CPressure', axis=1, level=1) 

df.xs('Mean_Force', axis=1, level=1) 
+0

感謝您的幫助!它也可以工作! – arnold

+0

@arnold如果你覺得這篇文章很有用,你可以加入它。 – piRSquared

相關問題