如何获取Julia DataFrame的列类型?
获取Julia中DataFrame的列类型
以下是几种实用方法来获取DataFrame的列类型,基于你提供的示例代码:
using DataFrames df = DataFrame(a = 1:4, b = ["a", "b", "c", "d"])
方法1:获取单列类型
如果只需要某一列的类型,直接对列对象调用eltype即可:
# 获取列a的类型 eltype(df.a) # 返回 Int64 # 也可以通过列索引/名称访问后获取类型 eltype(df[!, :b]) # 返回 String
方法2:一次性获取所有列的类型信息
使用schema函数可以返回包含所有列名和对应类型的Schema对象,方便批量查看:
sch = schema(df) # 提取列名列表 sch.names # 返回 [:a, :b] # 提取对应类型元组 sch.types # 返回 (Int64, String) # 直接打印完整schema信息 println(schema(df)) # 输出: # Schema: # a Int64 # b String
方法3:遍历所有列并输出类型
通过eachcol遍历每一列,同时获取列名和对应类型:
for (col_name, col_data) in eachcol(df, true) println("$col_name: $(eltype(col_data))") end # 输出: # a: Int64 # b: String
方法4:直接查看DataFrame显示信息
在REPL中直接输入DataFrame变量名,会自动展示每一列的类型,就像你提供的示例输出那样:
df # 输出: # 4×2 DataFrame # Row │ a b # │ Int64 String # ─────┼─────────────── # 1 │ 1 a # 2 │ 2 b # 3 │ 3 c # 4 │ 4 d
内容的提问来源于stack exchange,提问作者Georgery
相关产品推荐
相关产品推荐

