r-在大数据中以每个指示器的最大值而快速获取行



我得到了一个大数据。

n <- 7
dt <- data.table(id_1=sample(1:10^(n-1),10^n,replace=TRUE), other=sample(letters[1:20],10^n,replace=TRUE), val=rnorm(10^n,mean=10^4,sd=1000))
> structure(dt)
        id_1 other       val
    1: 914718     o  9623.078  
    2: 695164     f 10323.943
    3:  53186     h 10930.825
    4: 496575     p  9964.064
    5: 474733     l 10759.779
   ---                       
9999996: 650001     p  9653.125
9999997: 225775     i  8945.636
9999998: 372827     d  8947.095
9999999: 268678     e  8371.433
10000000: 730810     i 10150.311

,我想创建一个数据。对于指示器的每个值,id_1的每个值只有一个行,即val列中最大值的一个行。

以下代码似乎有效:

dt[, .SD[which.max(val)], by = .(id_1)]

但是,大桌子的速度非常慢。有更快的方法吗?

从技术上讲,这是此问题的重复但是答案没有真正解释过,因此,它去了:

dt[dt[, .(which_max = .I[val == max(val)]), by = "id_1"]$which_max]

内部表达基本发现,每个组根据id_1,最大值的行索引,并简单地返回这些索引,以便可以用来子集dt

但是,我有点惊讶我没有找到答案,这是:

setkey(dt, id_1, val)[, .SD[.N], by = "id_1"]

似乎在我的机器中也很快但这需要对行进行排序。

我不确定如何在R中进行操作,但是我所做的是按行读取,然后将这些行放入数据框架中。这非常快,发生在100 MB文本文件中的闪光灯中。

import pandas as pd
filename ="C:/Users/xyz/Downloads/123456789.012-01-433.txt"
filename =filename
with open(filename, 'r') as f:
    sample =[]          #creating an empty array
    for line in f:
        tag=line[:45].split('|')[5] # its a condition, you dont need this.
        if tag == 'KV-C901':
            sample.append(line.split('|')) # writing those lines to an array table
print('arrays are appended and ready to create a dataframe out of an array') 

最新更新