2017-06-28 44 views
1

我給出的以下大熊貓數據幀傳遞數組參數到我自己的2D函數

df 
         long  lat weekday hour 
dttm             
2015-07-03 00:00:38 1.114318 0.709553  6  0 
2015-08-04 00:19:18 0.797157 0.086720  3  0 
2015-08-04 00:19:46 0.797157 0.086720  3  0 
2015-08-04 13:24:02 0.786688 0.059632  3 13 
2015-08-04 13:24:34 0.786688 0.059632  3 13 
2015-08-04 18:46:36 0.859795 0.330385  3 18 
2015-08-04 18:47:02 0.859795 0.330385  3 18 
2015-08-04 19:46:41 0.755008 0.041488  3 19 
2015-08-04 19:47:45 0.755008 0.041488  3 19 

我還具有接收作爲輸入2個數組的函數:

import pandas as pd 
import numpy as np 

def time_hist(weekday, hour): 
    hist_2d=np.histogram2d(weekday,hour, bins = [xrange(0,8), xrange(0,25)]) 
    return hist_2d[0].astype(int) 

祝將我的2D功能應用到以下組的每個組:

df.groupby(['long', 'lat']) 

我試過傳遞* args到.apply():

df.groupby(['long', 'lat']).apply(time_hist, [df.weekday, df.hour]) 

但我得到一個錯誤:「箱的維數必須等於樣本x的維數。」

當然尺寸不匹配。整個想法是,我不知道哪個迷你[星期幾,小時]陣列發送給每個組。

我該怎麼做?

回答

1

務必:

import pandas as pd 
import numpy as np 

df = pd.read_csv('file.csv', index_col=0) 


def time_hist(x): 
    hour = x.hour 
    weekday = x.weekday 
    hist_2d = np.histogram2d(weekday, hour, bins=[xrange(0, 8), xrange(0, 25)]) 
    return hist_2d[0].astype(int) 


print(df.groupby(['long', 'lat']).apply(time_hist)) 

輸出:

long  lat  
0.755008 0.041488 [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,... 
0.786688 0.059632 [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,... 
0.797157 0.086720 [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,... 
0.859795 0.330385 [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,... 
1.114318 0.709553 [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,... 
dtype: object