【问题标题】:Unable to add a variable in Julia DataFrame无法在 Julia DataFrame 中添加变量
【发布时间】:2021-08-29 04:00:13
【问题描述】:

我正在尝试从文件夹中读取所有文件并尝试根据文件名创建文件名变量

我正在使用以下代码来执行此操作。但我无法添加让我知道文件名的变量 -

using DataFrame
using Queryverse
using VegaLite
using Statistics
using CSV
using Glob

path = "D:\\Udemy\\FInancial_Engineering_Lazy_Programmer\\Yfinance_Data"
files = glob("*.csv", path)

df_com = DataFrame()
for file in files
    df = CSV.File(file)
    df[:filename] = first(split(last(split(file, "\\")),"."))
    append!(df_com, df)
end

我收到以下错误 -

ERROR: ArgumentError: invalid index: :filename of type Symbol
Stacktrace:
 [1] to_index(i::Symbol)
   @ Base .\indices.jl:300
 [2] to_index(A::CSV.File{false}, i::Symbol)
   @ Base .\indices.jl:277
 [3] to_indices
   @ .\indices.jl:333 [inlined]
 [4] to_indices
   @ .\indices.jl:325 [inlined]
 [5] setindex!(A::CSV.File{false}, v::Tuple{SubString{String}, Vector{Symbol}}, I::Symbol)
   @ Base .\abstractarray.jl:1267
 [6] top-level scope
   @ .\REPL[161]:3

创建文件名没有问题,但将其添加到数据框时出现问题。以下代码可以正常工作并提供文件名,但无法将其添加为变量

for file in files
    println(first(split(last(split(file, "\\")),".")))
end

你能帮忙吗?

【问题讨论】:

    标签: julia julia-dataframe


    【解决方案1】:

    这是最简洁的方法:

    reduce(vcat,
           CSV.read.(files, DataFrame),
           source=:filename => chop.(basename.(files), tail=4))
    

    现在,让我在您的代码中添加一些 cmets,希望对您有所帮助:

    • 不推荐split(file, "\\"),因为它只适用于Windows,最好使用适用于所有操作系统的basename
    • 使用first(split(your_filename,"."))是不正确的,如果你的文件名中包含多个.会产生错误的结果; chop 最后四个字符更干净,因为你知道它们是 .csv
    • CSV.File(file) 不会产生 DataFrame 对象;这就是为什么后来df[:filename] = first(split(last(split(file, "\\")),".")) 失败的原因;更好地使用CSV.read(file, DataFrame) 来有效地创建一个数据框,在这种情况下你可以例如添加这样的列df.filename = first(split(last(split(file, "\")),"."))`
    • 更改代码上面的代码会起作用,但是使用vcat 比重复调用append! 更有效,因为vcat 针对合并多个数据帧进行了优化,reduce(vcat, ...) 部分确保您可以传递数据帧的向量(而不必列出它们);
    • 最后,vcat 相对于append! 的好处是您不必手动创建:filename 列,因为vcat 支持source 关键字参数来处理您的用例。

    我希望这些提示可以帮助您总体上使用 DataFrames.jl。

    【讨论】:

    • 非常感谢您的帮助。我试图结合来自 Stackoverflow 的多个代码来实现我知道的 Python 代码。我将尝试检查您提到的功能的详细文档。再次感谢您的及时回复:)
    • 非常感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-13
    • 2020-05-04
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2015-01-28
    相关资源
    最近更新 更多