【问题标题】:Julia replace nested for-loops by comprehensionsJulia 用推导替换嵌套的 for 循环
【发布时间】:2022-07-07 23:39:53
【问题描述】:

抱歉,我是 Julia 的初学者。我曾尝试用 Julia 中的理解替换嵌套的 for 循环,但没有成功:

dfc 是 12x8 DataFrameempty_rows = Vector{Int64}()。以下理解

[[push!(empty_rows,j) for j in 1:12] for i in 1:8 if ismissing(dfc[j,i])]

收到错误:ERROR: UndefVarError: j not defined

非常感谢您帮助解决问题

【问题讨论】:

  • 也许您还可以显示您想要替换的嵌套循环?恐怕很难从这个损坏的代码中判断出所需的输出应该是什么。

标签: julia list-comprehension


【解决方案1】:

我了解到您的数据框如下所示:

julia> df = DataFrame(rand([missing;1:8], 12, 8),:auto)
12×8 DataFrame
 Row │ x1      x2      x3      x4       x5       x6       x7      x8
     │ Int64?  Int64?  Int64?  Int64?   Int64?   Int64?   Int64?  Int64?
─────┼────────────────────────────────────────────────────────────────────
   1 │      5       7       3        6        7        8       2        8
   2 │      8       2       7        3        5        8       6        6
   3 │      2       2       4        7        4        3       4        7
   4 │      8       2       5        7        6        6       5        2
   5 │      1       3       1  missing        8        3       6        1
   6 │      2       8       7        2        3        3       8        3
   7 │      1       2       8        8        6  missing       2        4
   8 │      2       1       1        6        2  missing       4  missing
   9 │      3       2       8        8        6        2       8        5
  10 │      2       7       6        2        4        5       1        2
  11 │      3       7       5        2  missing        4       4        8
  12 │      2       4       5  missing        7        1       7        8

并且您想查找缺少值的行:

julia> findall(==(1), any(ismissing.(collect(row))) for row in eachrow(df))
5-element Vector{Int64}:
  5
  7
  8
 11
 12

甚至更短(结果一样):

findall(==(1),completecases(df))

【讨论】:

    猜你喜欢
    • 2020-06-03
    • 2018-05-21
    • 2019-06-06
    • 2016-07-14
    • 2021-08-09
    • 1970-01-01
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多