2017-04-20 179 views
1

我有一個ID欄和一些功能列的數據框。我希望看到每列值有多少個唯一ID的說明。「轉置」熊貓系列

下面的代碼工作,但我不知道是否有比to_frame().unstack().unstack()線,調換了.describe()的一系列結果,以數據框,其中列有百分位數,最大值,最小值一個更好的辦法...

def unique_ids(df): 
    rows = [] 
    for col in sorted(c for c in df.columns if c != id_col): 
     v = df.groupby(col)[id_col].nunique().describe() 
     v = v.to_frame().unstack().unstack() # Transpose 
     v.index = [col] 
     rows.append(v) 

    return pd.concat(rows) 

回答

3

似乎你需要改變:

v = v.to_frame().unstack().unstack() 

v = v.to_frame().T 

或者可能transpose最終DataFrame,也由col添加rename

df = pd.DataFrame({'ID':[1,1,3], 
        'E':[4,5,5], 
        'C':[7,8,9]}) 

print (df) 
    C E ID 
0 7 4 1 
1 8 5 1 
2 9 5 3 

def unique_ids(df): 
    rows = [] 
    id_col = 'ID' 
    for col in sorted(c for c in df.columns if c != id_col): 
     v = df.groupby(col)[id_col].nunique().describe().rename(col) 
     rows.append(v) 
    return pd.concat(rows, axis=1).T 

print (unique_ids(df)) 
    count mean  std min 25% 50% 75% max 
C 3.0 1.0 0.000000 1.0 1.00 1.0 1.00 1.0 
E 2.0 1.5 0.707107 1.0 1.25 1.5 1.75 2.0