在巨大的数据帧中在 R 中执行 CountIf超过 2000 万行 这基本上就是@Gregor-Thomas 在评论中给出的答案

如何解决在巨大的数据帧中在 R 中执行 CountIf超过 2000 万行 这基本上就是@Gregor-Thomas 在评论中给出的答案

我有一个包含 600 个代码(就像下面的代码)的数据框来匹配一个 2800 万行的数据框。我想查看第一个数据帧中的每个代码在第二个数据帧中出现的次数(两者都有一个包含匹配数据帧的列)。它基本上是一个 Countif(就像一个 Excel), 请参阅我有数据帧 1,示例如下:数据帧 1 中的代码是唯一的,600 个唯一代码,在数据帧 2 中它们会重复。

| Code 4 Dig| Name           |
| --------  | -------------- |
| 0111      | Name 1         |
| 0894      | Name 2         |
| 7895      | Name 3         |
| 8412      | Name 4         |

2800万行的header有点像这样(ID与我无关,只是想算一下第一个数据的code出现了多少次):

| Code 4 Dig| ID             |
| --------  | -------------- |
| 0894      | ID152           |
| 0894      | ID 25           |
| 0894      | ID10            |
| 7895      | ID 125          |

非常感谢!!

解决方法

这是一个 dplyr 方法。在我的电脑上,在 20M 行上运行大约需要一秒钟,在 200M 行上运行需要 4-7 秒。

library(dplyr)

big_table %>%                # take the big table
  count(code) %>%            # count how many appearances of each code
  left_join(lookup_table)    # join those counts to orig table to get `Name`
                             # note: any code not in lookup_table would show NA for `Name`

源数据:

lookup_table <- data.frame(code = 1:600,names = paste("Name",1:600))

big_table <- lookup_table %>%
  mutate(times = rpois(n(),34000)) %>%     # random times for each row  
  uncount(times) %>%                        # copy row this many times
  slice_sample(n = nrow(.))                 # to shuffle
,

这基本上就是@Gregor-Thomas 在评论中给出的答案

没有发布您自己解决问题的尝试,我只能猜测该解决方案是否适合您的用例。

# Load libraries
library(tidyverse)
library(data.table)

# Create example data
df1 <- tibble::tribble(
~"Code 4 Dig",~"Name","0111","Name 1","0894","Name 2","7895","Name 3","8412","Name 4"
  )

df2 <- tibble::tribble(
~"Code 4 Dig",~"ID","ID152","ID 25","ID10","ID 125"
  )

# Convert example dataframes to data.tables
setDT(df1)
setDT(df2)

# Set keys for joining
setkey(df1,`Code 4 Dig`)
setkey(df2,`Code 4 Dig`)

# Join the tables
Result <- df1[df2,nomatch=0]

# Summarise to get counts
counts <- Result[,.(counts = .N),by = `Code 4 Dig`]
counts
#>    Code 4 Dig counts
#> 1:       0894      3
#> 2:       7895      1

--

而且,为了显示它适用于 600 个数字 (df1) 和 2800 万行 (df2):

# Load libraries
library(tidyverse)
library(data.table)

# Create example data
pick.nums <- function(n) {
  floor(10^(sample(3:8,n,replace = TRUE))*runif(n))
}

pick.nums(5)
#> [1] 52198541  8972430    98870      720  4013067

df1 <- data.frame("Code 4 Dig" = c(pick.nums(600)),"Name" = paste("name_",pick.nums(600),sep = ""),check.names = FALSE)

df2 <- data.frame("Code 4 Dig" = c(pick.nums(28000000)),"ID" = paste("ID_",c(pick.nums(28000000)),check.names = FALSE)

# Convert example dataframes to data.tables
setDT(df1)
setDT(df2)

# Set keys for joining
setkey(df1,by = `Code 4 Dig`]
counts
#>      Code 4 Dig counts
#>   1:          9   5166
#>   2:         13   5122
#>   3:         24   5193
#>   4:         25   5198
#>   5:         30   5227
#>  ---                  
#> 437:    8841332      1
#> 438:    8966071      2
#> 439:    8969648      1
#> 440:    9040953      1
#> 441:    9591721      1
,

28M 行对于 R 来说并不是很大。可以使用基础 R、dplyr 或 data.table 来实现。

我将借用 jared_mamrot 的示例,并在 dplyr 和 dtplyr(又名更简单的 data.table)中显示速度。

下面的 dplyr 代码大约需要 6 秒才能运行。坦率地说,如果这是一次性脚本或每月一次的脚本,那么我不会费心加快速度。如果您正在为客户按需运行此程序并且需要在不到一秒的时间内获得结果,请继续使用 dtplyr 或 data.table 答案。

library(tidyverse)

pick.nums <- function(n) {
  floor(10^(sample(3:8,replace = TRUE))*runif(n))
}

df1 <- data.frame("Code 4 Dig" = c(pick.nums(600)),check.names = FALSE)

microbenchmark::microbenchmark({
  result <- df1 %>% 
    inner_join(df2) %>% 
    group_by(`Code 4 Dig`) %>%
    summarise(count = n())
},times = 3)
# Unit: seconds
#      min       lq     mean   median       uq      max neval
# 4.569945 5.466638 5.986419 6.363332 6.694656 7.025981     3

str(result)
tibble [437 x 2] (S3: tbl_df/tbl/data.frame)
$ Code 4 Dig: num [1:437] 7 9 38 59 79 88 91 100 103 105 ...
$ count     : int [1:437] 10556 5207 5175 5179 5145 5162 5248 5214 5228 5282 ...

如果你需要它运行得非常快,那么 dtplyr 方法可以在 0.035 秒内完成连接和计数。但是,在进行联接之前,输入数据需要 1.9 秒的时间。所以它仍然需要几秒钟。

library(dtplyr)

microbenchmark::microbenchmark(
dt1 <- df1 %>% lazy_dt(key_by = `Code 4 Dig`),dt2 <- df2 %>% lazy_dt(key_by = `Code 4 Dig`),times = 3)
# Unit: milliseconds
#         min         lq        mean    median          uq         max
#    1.039201    1.17975    1.575267    1.3203    1.843301    2.366301
# 1708.594001 1737.07515 1952.342434 1765.5563 2074.216651 2382.877001


microbenchmark::microbenchmark({
  resultdt <- dt1 %>% 
    inner_join(dt2) %>% 
    group_by(`Code 4 Dig`) %>%
    summarise(count = n()) %>%
    as_tibble()
},times = 3)
# Unit: milliseconds
# min      lq    mean  median       uq     max neval
# 29.4548 32.8968 35.3977 36.3388 38.36915 40.3995     3

str(resultdt)
tibble [437 x 2] (S3: tbl_df/tbl/data.frame)
$ Code 4 Dig: num [1:437] 7 9 38 59 79 88 91 100 103 105 ...
$ count     : int [1:437] 10556 5207 5175 5179 5145 5162 5248 5214 5228 5282 ...

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-