【问题标题】:Julia: how to compute a particular operation on certain columns of a DataframeJulia:如何计算 Dataframe 某些列的特定操作
【发布时间】:2019-11-23 12:35:53
【问题描述】:

我有以下数据框

using DataFrames, Statistics
df = DataFrame(name=["John", "Sally", "Kirk"], 
               age=[23., 42., 59.],
               children=[3,5,2], height = [180, 150, 170])

print(df)

3×4 DataFrame
│ Row │ name   │ age     │ children │ height │
│     │ String │ Float64 │ Int64    │ Int64  │
├─────┼────────┼─────────┼──────────┼────────┤
│ 1   │ John   │ 23.0    │ 3        │ 180    │
│ 2   │ Sally  │ 42.0    │ 5        │ 150    │
│ 3   │ Kirk   │ 59.0    │ 2        │ 170    │

我可以按如下方式计算列的平均值:

println(mean(df[:4]))
166.66666666666666

现在我想获取所有数字列的平均值并尝试了以下代码:

x = [2,3,4]
for i in x
  print(mean(df[:x[i]]))
end

但收到以下错误消息:

MethodError: no method matching getindex(::Symbol, ::Int64)

Stacktrace:
 [1] top-level scope at ./In[64]:3

我该如何解决这个问题?

【问题讨论】:

  • 作为一般评论 - 很快df[col] 语法将被弃用。所以几天后推荐的模式将是df[!, col] 访问列而不复制它,df[:, col] 复制它。

标签: dataframe julia mean


【解决方案1】:

您正在尝试使用指定列位置的整数索引来访问DataFrame 的列。您应该只在i 之前使用不带任何: 的整数值,这将创建符号:i,但您没有名为i 的列。

x = [2,3,4]
for i in x
  println(mean(df[i])) # no need for `x[i]`
end

您还可以使用表示列名称的Symbol 来索引DataFrame

x = [:age, :children, :height];

for c in x
    println(mean(df[c]))
end

您在尝试时收到以下错误,因为您尝试访问符号 :xith 索引,这是一个未定义的操作。

MethodError: no method matching getindex(::Symbol, ::Int64)

请注意,:4 只是 4

julia> :4
4

julia> typeof(:4)
Int64

【讨论】:

    【解决方案2】:

    这是一个实际上选择所有Number 列的单行:

    julia> mean.(eachcol(df[findall(x-> x<:Number, eltypes(df))]))
    3-element Array{Float64,1}:
      41.333333333333336
       3.3333333333333335
     166.66666666666666
    

    对于很多场景describe其实更方便:

    julia> describe(df)
    4×8 DataFrame
    │ Row │ variable │ mean    │ min  │ median │ max   │ nunique │ nmissing │ eltype   │
    │     │ Symbol   │ Union…  │ Any  │ Union… │ Any   │ Union…  │ Nothing  │ DataType │
    ├─────┼──────────┼─────────┼──────┼────────┼───────┼─────────┼──────────┼──────────┤
    │ 1   │ name     │         │ John │        │ Sally │ 3       │          │ String   │
    │ 2   │ age      │ 41.3333 │ 23.0 │ 42.0   │ 59.0  │         │          │ Float64  │
    │ 3   │ children │ 3.33333 │ 2    │ 3.0    │ 5     │         │          │ Int64    │
    │ 4   │ height   │ 166.667 │ 150  │ 170.0  │ 180   │         │          │ Int64    │
    

    【讨论】:

      【解决方案3】:

      在问题中println(mean(df[4])) 也可以(而不是println(mean(df[:4])))。

      因此我们可以写

      x = [2,3,4]
      for i in x
        println(mean(df[i]))
      end
      

      哪个有效

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-01-25
        • 1970-01-01
        • 1970-01-01
        • 2017-12-21
        • 1970-01-01
        • 2015-11-13
        • 2021-08-15
        • 2020-10-10
        相关资源
        最近更新 更多