2016-07-08 5 views
0

私はCloudera VM 5.2.0 pandas 0.18.0を使用しています。pandas group選択列で

私は次のようなデータを持っている

adclicksDF = pd.read_csv('/home/cloudera/Eglence/ad-clicks.csv', 
       parse_dates=['timestamp'], 
     skipinitialspace=True).assign(adCount=1) 

adclicksDF.head(n=5) 
Out[65]: 
      timestamp txId userSessionId teamId userId adId adCategory \ 
0 2016-05-26 15:13:22 5974   5809  27  611  2 electronics 
1 2016-05-26 15:17:24 5976   5705  18 1874 21  movies 
2 2016-05-26 15:22:52 5978   5791  53 2139 25 computers 
3 2016-05-26 15:22:57 5973   5756  63  212 10  fashion 
4 2016-05-26 15:22:58 5980   5920  9 1027 20  clothing 

    adCount 
0  1 
1  1 
2  1 
3  1 
4  1 

私は、私は多くの列adCategory、idUserをagrupadoに追加するフィールドのタイムスタンプのための

adCategoryclicks = adclicksDF[['timestamp','adId','adCategory','userId','adCount']] 

agrupadoDF = adCategoryclicks.groupby(pd.Grouper(key='timestamp', freq='1H'))['adCount'].agg(['count','sum']) 

agrupadoDF.head(n=5)  
Out[68]: 
        count sum 
timestamp      
2016-05-26 15:00:00  14 14 
2016-05-26 16:00:00  24 24 
2016-05-26 17:00:00  13 13 
2016-05-26 18:00:00  16 16 
2016-05-26 19:00:00  16 16 

でグループをやりたいです。 どうすればいいですか?

答えて

0

存在は、joinによってそうaggreagate各groupためuserIdadCategoryで複数の値である:よりよい出力に変更され、このサンプルの最後の2つの日時で

print (adclicksDF) 
      timestamp txId userSessionId teamId userId adId adCategory \ 
0 2016-05-26 15:13:22 5974   5809  27 611  2 electronics 
1 2016-05-26 15:17:24 5976   5705  18 1874 21  movies 
2 2016-05-26 15:22:52 5978   5791  53 2139 25 computers 
3 2016-05-26 16:22:57 5973   5756  63 212 10  fashion 
4 2016-05-26 16:22:58 5980   5920  9 1027 20  clothing 

    adCount 
0  1 
1  1 
2  1 
3  1 
4  1 
#cast int to string 
adclicksDF['userId'] = adclicksDF['userId'].astype(str) 
adCategoryclicks = adclicksDF[['timestamp','adId','adCategory','userId','adCount']] 


agrupadoDF = adCategoryclicks.groupby(pd.Grouper(key='timestamp', freq='1H')) 
          .agg({'adCount': ['count','sum'], 
            'userId': ', '.join, 
            'adCategory': ', '.join}) 

agrupadoDF.columns = ['adCategory','count','sum','userId'] 

print (agrupadoDF) 
             adCategory count sum \ 
timestamp               
2016-05-26 15:00:00 electronics, movies, computers  3 3 
2016-05-26 16:00:00    fashion, clothing  2 2 

           userId 
timestamp        
2016-05-26 15:00:00 611, 1874, 2139 
2016-05-26 16:00:00  212, 1027 
関連する問題