## 为什么group_by - > filter - >在R中汇总比熊猫更快？内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (1)
• 关注 (0)
• 查看 (31)

R代码（在我的系统上大约需要2ms）：

``````df = data.frame(col_a = sample(letters[1:3],20,T),
col_b = sample(1:2,20,T),
col_c = sample(letters[1:2],20,T),
col_d = sample(c(4,2),20,T)
)

microbenchmark::microbenchmark(
a = df %>%
group_by(col_a, col_b) %>%
summarise(
a = sum(col_c == 'a'),
b = sum(col_c == 'b'),
c = a/b
) %>%
ungroup()
)

``````

``````df = pd.DataFrame({
'col_a': np.random.choice(['a','b','c'],N),
'col_b': np.random.choice([1,2],N),
'col_c': np.random.choice(['a', 'b'],N),
'col_d': np.random.choice(['4', '2'],N),
})
%%timeit
df1 = df.groupby(['col_a', 'col_b']).agg({
'col_c':[
('a',lambda x: (x=='a').sum()),
('b',lambda x: (x=='b').sum())
]}).reset_index()
df1['rat'] = df1.col_c.a/df1.col_c.b
``````

### 1 个回答

``````df.groupby(['col_a', 'col_b', 'col_c'])\
.count()\
.unstack()\
.assign(rat = lambda x: x.col_d.a/x.col_d.b)

4.96 ms ± 169 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
``````