在大 df 上进行 Groupby 或聚合

发布于 2025-01-10 08:32:20 字数 979 浏览 0 评论 0原文

我不明白如何对 R 中的大型 df 进行分组。

第 0-12 列是标识符,是唯一的,我想将它们保留为原样,

我已经尝试了多种变体,

aggregate(cbind(names(preferences[-c(0, 12)])) ~ 
            cbind(names(preferences[c(0, 12)])), data=preferences, FUN=sum)

我得到了

Error in model.frame.default(formula = cbind(names(preferences[-c(0, 12)])) ~  : 
  variable lengths differ (found for 'cbind(names(preferences[c(0, 12)]))')

a  b     c   d   e
1  f(1)  11  2   15
1  f(1)  12  2   15
2  f(2)  13  4   3
2  f(2)  14  6   4
3  f(3)  15  5   6

a  b     c   d   e
1  f(1)  23  4   30
2  f(2)  27  10  7
3  f(3)  15  5   6

Python 等效项 < code>df[11:624].groupby(by=col11)

df 是 48GB,所以速度很重要(python 由于内存不足(250GB)

而崩溃)收到 答案 我去看了一些基准测试 这太快了!!!!

I'm not understanding how to groupby on a large df in R.

Columns 0-12 are identifiers, unique, and I would like to leave them as is

I've tried a number of variations of this

aggregate(cbind(names(preferences[-c(0, 12)])) ~ 
            cbind(names(preferences[c(0, 12)])), data=preferences, FUN=sum)

I'm getting

Error in model.frame.default(formula = cbind(names(preferences[-c(0, 12)])) ~  : 
  variable lengths differ (found for 'cbind(names(preferences[c(0, 12)]))')

a  b     c   d   e
1  f(1)  11  2   15
1  f(1)  12  2   15
2  f(2)  13  4   3
2  f(2)  14  6   4
3  f(3)  15  5   6

a  b     c   d   e
1  f(1)  23  4   30
2  f(2)  27  10  7
3  f(3)  15  5   6

Python equivalent df[11:624].groupby(by=col11)

df is 48GB so speed matters (python crashes due to a lack of memory(250GB))

After receiving an answer I went and looked at some benchmarks and this is fast as heck!!!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

世界等同你 2025-01-17 08:32:20
library(data.table)

setDT(df)

x <- names(df)[13:ncol(df)]

y <- names(df)[1:12]

df_2 <- df[, lapply(.SD, \(i) sum(i)), .SDcols=x, by=y]

不过要注意 R 与 Python 中的索引。 R 从 1 开始计数(而 Python 的索引为零)

library(data.table)

setDT(df)

x <- names(df)[13:ncol(df)]

y <- names(df)[1:12]

df_2 <- df[, lapply(.SD, \(i) sum(i)), .SDcols=x, by=y]

Though be aware of indexing in R vs Python. R starts counting from 1 (whereas Python has zero indexing)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文