【发布时间】:2018-01-07 03:37:44
【问题描述】:
我经常发现自己尝试使用 R 等效于 groupby 然后 mutate,但正如许多人指出的那样,简单地使用 groupby 和 apply 会遇到严重的性能问题。所以我的问题是,在 pandas 中对数据框进行分组的最佳(最高性能)方法是什么,然后根据该组中的某些条件,根据一些计算添加一个新列?
(我进行了搜索和搜索,但没有找到任何关于如何使用 numpy 在 pandas 中对自定义函数进行矢量化的指南/步骤。所有类似问题的答案都是针对具体情况的,不能很好地概括。)
示例数据:
df
Out[17]:
ID ID2 col1 col2 col3 value
0 1 J 333.5 333.3 333.4 cat
1 1 S 333.5 333.3 333.8
2 2 J 333.7 333.3 333.8 cat
3 2 S 333.7 333.3 333.4 dog
4 3 L 333.7 333.8 333.9
5 3 D 333.8 333.8 333.9
6 4 S 333.8 333.6 333.7 cat
7 4 J 333.8 333.2 333.8
8 4 J 333.8 333.7 333.9
9 4 L 333.8 333.3 333.4 cat
这里有一些例子,我经常遇到:
1) apply 函数根据条件分组,将这些结果与原始数据帧一起返回。
df.groupby(by=['ID']).apply(myfunc)
def myfunc(group):
group['new_col'] = len(group.query('''ID2=='T' & (col1>=col3 | px<=col2)''').unique())
return group
2) 与 1) 类似,但仅根据某些条件更新一个现有列,然后将该结果与原始数据帧一起返回。
df.groupby(by=['ID']).apply(update_func)
def update_func(group):
if 'S' in group['ID2'].values:
group.loc[(group['value']=='cat'), 'other_column'] = False
return group
【问题讨论】:
-
你有什么具体的例子吗?这是一个开放式问题,被认为是本论坛的广泛问题。
-
@ScottBoston 我发布了几个示例,它们在当前形式中是否过于宽泛?
-
是的,如果您有输入和预期输出,这会有所帮助。这是我的看法。
-
在示例 1 中,您的函数返回值应仅为
len(group... .unique()),然后在您的函数中调用df['new_col'] = df.groupby(by='ID').apply(myfunc)。返回值而不是整个数据框,然后将这些值设置为调用中的新列。 -
在示例 2 中,我认为您正在尝试过滤数据框。使用
groupby和filter.... 尝试这样的操作:df.groupby('ID').filter(lambda x: x.ID2.isin(['S']).any()).query('value == "cat"')
标签: pandas performance numpy vectorization pandas-groupby