2017-06-28 97 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