如何在 julia 数据框中获取列的 dtypes

Moh*_* ah 3 julia

如何在 julia 中获取所有列和特定列的 dtypes。具体来说df.dtypes,朱莉娅中的熊猫相当于什么?

例如,我有一个如下所示的 df,

? Row ? Id    ? name   ? item location ?
?     ? Int64 ? String ? String        ?
????????????????????????????????????????
? 1   ? 1     ? A      ? xyz           ?
? 2   ? 2     ? B      ? abc           ?
? 3   ? 3     ? C      ? def           ?
? 4   ? 4     ? D      ? ghi           ?
? 5   ? 5     ? E      ? xyz           ?
? 6   ? 6     ? F      ? abc           ?
? 7   ? 7     ? G      ? def           ?
? 8   ? 8     ? H      ? ghi           ?
? 9   ? 9     ? I      ? xyz           ?
? 10  ? 10    ? J      ? abc           ?
Run Code Online (Sandbox Code Playgroud)

预期输出:

{'id':  Int64, 'name': String, 'item location': String}
Run Code Online (Sandbox Code Playgroud)

如何获得 dtypes,即Int64 ? String ? String 在 Julia 中?

Bog*_*ski 5

您已经指定了两个不同的预期输出,所以我在这里展示了如何获得这两个输出:

julia> df = DataFrame("Id" => 1, "name" => "A", "item_location" => "xyz")
1×3 DataFrame
? Row ? Id    ? name   ? item_location ?
?     ? Int64 ? String ? String        ?
????????????????????????????????????????
? 1   ? 1     ? A      ? xyz           ?

julia> eltype.(eachcol(df))
3-element Array{DataType,1}:
 Int64
 String
 String

julia> Dict(names(df) .=> eltype.(eachcol(df)))
Dict{String,DataType} with 3 entries:
  "Id"            => Int64
  "name"          => String
  "item_location" => String
Run Code Online (Sandbox Code Playgroud)

此外,如果您想将结果存储在 aDataFrame而不是 aDict您可以编写(请参阅此处的mapcols文档):

julia> mapcols(eltype, df)
1×3 DataFrame
? Row ? Id       ? name     ? item_location ?
?     ? DataType ? DataType ? DataType      ?
?????????????????????????????????????????????
? 1   ? Int64    ? String   ? String        ?
Run Code Online (Sandbox Code Playgroud)

如果你想有一个NamedTuple存储这些信息写入(的文件Tables.columntable在这里):

julia> map(eltype, Tables.columntable(df))
(Id = Int64, name = String, item_location = String)

Run Code Online (Sandbox Code Playgroud)

(在这种情况下请注意,对于非常宽的表,这可能会产生一些额外的编译成本,因为每次调用它时都可能会获得一种新类型的NamedTuple

  • 美妙之处在于基本解决方案不是 DataFrames.jl 特定的。它只是应用于数据框的 Julia Base。这在 Julia 中很常见,因为事情组合得很好。我们只使用广播(“.”)、“eltype”(来自 Base)和“eachcol”(也来自 Base)。`mapcols` 和 `Tables.columntable` 是特定于包的 - 我将为它们添加指向文档的链接。一般来说,这与 Pandas 是一种非常不同的理念,Pandas 的大部分功能都打包在一个包中。在 Julia 中,包可以有更有限的 API,因为多个调度可以处理组合部分。 (3认同)
  • 相反 - 这些都是很好的问题。对于刚接触 Julia 的人来说,需要了解的关键是:1)您应该很好地学习 Base Julia,2)大多数软件包将尝试最大程度地利用这些知识。从长远来看(在学习 Base 之后),这意味着当您开始使用新包时,需要学习的东西要少得多,并且您可以期望两个完全不相关的包开箱即用,无需任何粘合接口即可一起工作。一个很好的例子是 https://julialang.org/blog/2019/01/fluxdiffeq/,它展示了混合微分方程和深度学习包。 (2认同)