2017-07-28 83 views
10

例如操作習慣的方法,你是怎麼做到的大熊貓下述R data.table操作:什麼是執行聚合和重命名大熊貓

PATHS[,.(completed=sum(exists), missing=sum(not(exists)), total=.N, 'size (G)'=sum(sizeMB)/1024), by=.(projectPath, pipelineId)] 

即分組projectPathpipelineId,使用可能的自定義函數彙總某些列 ,然後重命名結果列。

輸出應無分層索引的數據幀,例如:

     projectPath pipelineId completed missing size (G) 
/data/pnl/projects/TRACTS/pnlpipe   0  2568  0 45.30824 
/data/pnl/projects/TRACTS/pnlpipe   1  1299  0 62.69934 
+0

你有,你在這個問題粘貼一個樣本輸入數據幀? –

回答

15

您可以使用groupby.agg

df.groupby(['projectPath', 'pipelineId']).agg({ 
     'exists': {'completed': 'sum', 'missing': lambda x: (~x).sum(), 'total': 'size'}, 
     'sizeMB': {'size (G)': lambda x: x.sum()/1024} 
    }) 

採樣運行

df = pd.DataFrame({ 
     'projectPath': [1,1,1,1,2,2,2,2], 
     'pipelineId': [1,1,2,2,1,1,2,2], 
     'exists': [True, False,True,True,False,False,True,False], 
     'sizeMB': [120032,12234,223311,3223,11223,33445,3444,23321] 
    }) 

df1 = df.groupby(['projectPath', 'pipelineId']).agg({ 
     'exists': {'completed': 'sum', 'missing': lambda x: (~x).sum(), 'total': 'size'}, 
     'sizeMB': {'size (G)': lambda x: x.sum()/1024} 
    }) 
​ 
df1.columns = df1.columns.droplevel(0) 
​ 
df1.reset_index() 

enter image description here


更新:如果你真的要自定義的聚集,而無需使用過時的嵌套的字典語法,你可以隨時使用groupby.apply並從每個組返回系列對象:

df.groupby(['projectPath', 'pipelineId']).apply(
    lambda g: pd.Series({ 
      'completed': g.exists.sum(), 
      'missing': (~g.exists).sum(), 
      'total': g.exists.size, 
      'size (G)': g.sizeMB.sum()/1024 
     }) 
).reset_index() 

enter image description here

+0

非常好的例子。尼斯。 +1 –

+0

@ScottBoston謝謝。 – Psidom

+0

我想接受這個答案,但他們很快就會棄用.agg()中的嵌套字典:http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#deprecate-groupby-agg-with -a-dictionary-when-renaming – reckbo

1

我相信新的0.20,更「idiomati C」的方式,是這樣的(其中,該嵌套字典的第二層基本上由一個所附.rename方法替換):

中的R ...(completed=sum(exists), missing=sum(not(exists)), total=.N, 'size (G)'=sum(sizeMB)/1024), by=.(projectPath, pipelineId)]...,變得

編輯:在pd.DataFrame.groupby()使用as_index=False防止多指標在最後的DF

df.groupby(['projectPath', 'pipelineId'], as_index=False).agg({ 
    'exists': 'sum', 
    'pipelineId': 'count', 
    'sizeMB': lambda s: s.sum()/1024 
}).rename(columns={'exists': 'completed', 
        'pipelineId': 'total', 
        'sizeMB': 'size (G)'}) 

然後,我可能只是添加其他行的逆「存在」 - >「失蹤」:

df['missing'] = df.total - df.completed 

如在Jupyter筆記本測試的示例,下面有由pd.read_csv()導入到熊貓數據幀46條總流水線路徑一個模擬目錄樹,我稍微修改所討論的例子以在隨機數據在1000-100k核苷酸鹼基之間的DNA串的形式,而不是創建Mb大小的文件。儘管如此,非離散數據庫仍然可以計算,使用NumPy的np.mean()集合pd.Series對象可用於df.agg調用該過程,但lambda s: s.mean()將是更簡單的方法。

例如,,

df_paths.groupby(['TRACT', 'pipelineId']).agg({ 
    'mean_len(project)' : 'sum', 
    'len(seq)' : lambda agg_s: np.mean(agg_s.values)/1e9 
}).rename(columns={'len(seq)': 'Gb', 
        'mean_len(project)': 'TRACT_sum'}) 

這裏的「地域」是一個類別的一個級別更高「pipelineId」的目錄樹,這樣,在這個例子中,你可以看到有46個總獨特的管道 - 2「地域」層AB/AC x 6「pipelineId」/「project」的sx 4二進制組合00,01,10,11(減2個GNU並行做成第三個topdir的項目;見下文)。因此,在新的agg中,統計數據將項目級別的平均值轉換爲每個TRACT所有相關項目的總和。

enter image description here

df_paths = pd.read_csv('./data/paths.txt', header=None, names=['projectPath']) 
# df_paths['projectPath'] = 
df_paths['pipelineId'] = df_paths.projectPath.apply(
    lambda s: ''.join(s.split('/')[1:5])[:-3]) 
df_paths['TRACT'] = df_paths.pipelineId.apply(lambda s: s[:2]) 
df_paths['rand_DNA'] = [ 
    ''.join(random.choices(['A', 'C', 'T', 'G'], 
          k=random.randint(1e3, 1e5))) 
    for _ in range(df_paths.shape[0]) 
] 
df_paths['len(seq)'] = df_paths.rand_DNA.apply(len) 
df_paths['mean_len(project)'] = df_paths.pipelineId.apply(
    lambda pjct: df_paths.groupby('pipelineId')['len(seq)'].mean()[pjct]) 
df_paths 

enter image description here