将数组参数传递给我在Pandas groupby

时间:2017-06-28 13:04:57

标签: python pandas-groupby

我获得了以下pandas dataframe

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 个答案:

答案 0 :(得分: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