2017-09-23 38 views
2

的數據幀我有一個DASK數據框,看起來像這樣:機組A DASK數據幀,併產生聚集

url  referrer session_id ts     customer 
url1 ref1  xxx  2017-09-15 00:00:00 a.com 
url2 ref2  yyy  2017-09-15 00:00:00 a.com 
url2 ref3  yyy  2017-09-15 00:00:00 a.com 
url1 ref1  xxx  2017-09-15 01:00:00 a.com 
url2 ref2  yyy  2017-09-15 01:00:00 a.com 

我想組URL和時間戳,聚合列值的數據,併產生一個數據幀那會看起來是這樣,而不是:

customer url ts     page_views visitors referrers 
a.com url1 2017-09-15 00:00:00 1   1  [ref1] 
a.com url2 2017-09-15 00:00:00 2   2  [ref2, ref3] 

火花SQL,我可以做到這一點,如下所示:

select 
    customer, 
    url, 
    ts, 
    count(*) as page_views, 
    count(distinct(session_id)) as visitors, 
    collect_list(referrer) as referrers 
from df 
group by customer, url, ts 

有沒有什麼辦法可以與Dask dataframes做到這一點?我試過,但我只能單獨計算聚合列如下:

# group on timestamp (rounded) and url 
grouped = df.groupby(['ts', 'url']) 

# calculate page views (count rows in each group) 
page_views = grouped.size() 

# collect a list of referrer strings per group 
referrers = grouped['referrer'].apply(list, meta=('referrers', 'f8')) 

# count unique visitors (session ids) 
visitors = grouped['session_id'].count() 

,但我似乎無法找到以產生組合數據幀,我需要一個好辦法。

+0

有沒有一個很好的方式來做到這一點在熊貓?這種方式是否適用於dask.dataframe? – MRocklin

回答

1

下確實工作:

gb = df.groupby(['customer', 'url', 'ts']) 
gb.apply(lambda d: pd.DataFrame({'views': len(d), 
    'visitiors': d.session_id.count(), 
    'referrers': [d.referer.tolist()]})).reset_index() 

(假設遊客需要按照上面的SQL唯一的) 你不妨定義輸出的meta

+0

不錯!如果我從數據中構建一個'pd.DataFrame',它會將所有數據強制到一臺機器上的內存中嗎?現在這是一個玩具的例子,但真正的工作將與千兆字節的分佈式數據一起工作。 –

+0

它似乎與您的數據完全一樣;你應該嘗試提供一個元參數http://dask.pydata.org/en/latest/dataframe-api.html#dask.dataframe.groupby.DataFrameGroupBy.apply – mdurant

+0

你是對的,它與我指定的數據完全一致它在這個例子中。 它不適用於從分區拼花地板讀取的稍大一點的數據。我想弄清楚那個問題到底是什麼問題 - 我會用我的數據樣本在dask中提出一個問題。 Stackoverflow看起來不是一個好的地方。謝謝! –