【发布时间】:2017-07-09 15:55:01
【问题描述】:
我有一个整数数组说
theIndex = [ 1 2 6 7 17 2]
我有一个数据框,其中一列 dataset[:id] 包含整数说
dataset = DataFrame(id=[ 1, 1, 2, 2, 3, 3, 3, 4, 4, 4])
我想选择数据集中属于索引的所有观察值。如果它们在索引中出现两次(或更多),我想选择它们两次(或更多)
目前,我正在以愚蠢的方式做这件事。
theIndex = [ 1 2 6 7 17 2]
dataset = DataFrame(id=[ 1, 1, 2, 2, 3, 3, 3, 4, 4, 4])
dataset2 = DataFrame(id=Int64[])
for ii1=1:size(theIndex,2)
for ii2=1:size(dataset[:id],1)
any(i->i.==dataset[ii2,:id],theIndex[ii1]) ?
push!(dataset2,dataset[ii2,:id]) : nothing
end
end
还有更优雅的解决方案吗?
【问题讨论】:
-
dataset[vcat([[j for j in 1:nrow(dataset) if dataset[j, :id] == i] for i in theIndex]...),:]跨度>
-
或
dataset[vcat(map(i->filter(j->dataset[j,:id]==i, 1:nrow(dataset)), theIndex)...),:] -
非常感谢它更紧凑/优雅。但对于大型数据集来说相当慢。有没有什么命令。这可以避免做两个循环。
-
如果你想处理重复的值,我相信你必须做两个循环(显式或隐式)。如果
theIndex的唯一值基数较低,您可以缓存内部循环的结果以避免多次执行。 -
其实我刚刚意识到你可以做一个嵌套理解
[j for i in theIndex for j in 1:nrow(dataset) if dataset[j, :id] == i]
标签: dataframe subset julia bootstrap-4 any