Julia:如何在 Dataframe 的某些列上计算特定操作

Julia: how to compute a particular operation on certain columns of a Dataframe

我有以下数据框

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

我该如何解决这个问题?

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

因此我们可以写

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

有效

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

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

您还可以使用表示列名称的 SymbolDataFrame 进行索引。

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

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

您尝试访问符号 :x 的第 i 个索引时出现以下错误,这是一个未定义的操作。

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

请注意 :4 只是 4

julia> :4
4

julia> typeof(:4)
Int64

这里是一个 one-liner,实际上选择了所有 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    │