天才们。我是 Julia 的新手,但有一个雄心勃勃的目标。 到目前为止,我正在尝试跟踪流,当然这是一个自动过程。
- 将数据从 csv 文件读取到 DataFrame
- 检查数据,然后根据 DataFrames 数据类型创建数据库表
- 将数据从 DataFrame 插入到创建的表(例如 SQLite)
我现在坚持第二名,因为例如列的数据类型“Vector{String15}”。 我正在努力如何将数据类型反射(reflect)到创建表的查询。 我的意思是我在(a)(b)以下找不到任何解决方案。
fname = string( @__DIR__,"/","testdata/test.csv")
df = CSV.read( fname, DataFrame )
last = ncol(df)
for i = 1:last
col[i] = typeof(df[!,i]) # ex. Vector{String15}
if String == col[i] # (a) does not work
# create table sql
# expect
query = 'create table testtable( col1 varchar(15),....'
elseif Int == col[i] # (b) does not work
# create table sql
# expect
query = 'create table testtable( col1 int,....'
end
・
・
end
我很奇怪,
- 无论如何,我真的必须从“Vector{String15}”获取表格列的类型吗?
- DataFrames 是否有实用方法来执行此操作?
- 需要结合其他模块来实现吗?
我期待您的明智提示,感谢您的任何进展。
最佳答案
以下是两种方法的实现方法:
julia> using DataFrames
julia> using CSV
julia> df = CSV.read("test.csv", DataFrame)
3×3 DataFrame
Row │ a b c
│ String15 Int64 Float64
─────┼─────────────────────────────
1 │ a1234567890 1 1.5
2 │ b1234567890 11 11.5
3 │ b1234567890 111 111.5
julia> using SQLite
julia> db = SQLite.DB("test.db")
SQLite.DB("test.db")
julia> SQLite.load!(df, db, "df")
"df"
julia> SQLite.columns(db, "df")
(cid = [0, 1, 2], name = ["a", " b", " c"], type = ["TEXT", "INT", "REAL"], notnull = [1, 1, 1], dflt_value = [missing, missing, missing], pk = [0, 0, 0])
julia> query = DBInterface.execute(db, "SELECT * FROM df")
SQLite.Query(SQLite.Stmt(SQLite.DB("test.db"), 4), Base.RefValue{Int32}(100), [:a, Symbol(" b"), Symbol(" c")], Type[Union{Missing, String}, Union{Missing, Int64}, UnionMissing, Float64}], Dict(:a => 1, Symbol(" c") => 3, Symbol(" b") => 2), Base.RefValue{Int64}(0))
julia> DataFrame(query)
3×3 DataFrame
Row │ a b c
│ String Int64 Float64
─────┼─────────────────────────────
1 │ a1234567890 1 1.5
2 │ b1234567890 11 11.5
3 │ b1234567890 111 111.5
如果您需要更多解释,Julia for Data Analysis 第 8 章对此进行了介绍。本章将于 1-2 周内在 MEAP 上发布(源代码已在 https://github.com/bkamins/JuliaForDataAnalysis 上提供)
关于database - 数据框到数据库表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72695370/