Julia编程语言基本语法

1、Julia读取/保存csv数据
读取:

using CSV
df = CSV.read("mydata.csv")

保存为csv格式:

# 创建 DataFrame
df = DataFrame(height = h, discharge = q)
# 将 DataFrame 写入 CSV 文件
CSV.write("output.csv", df)

报错:UndefVarError: writeshortest not defined
解决:https://discourse.julialang.org/t/csv-write-writeshortest-error/90336/8
Converting the entire data frame content into string type:CSV.write(“temp.csv”,string.(df))
或者更新CSV版本。

文件读写常用函数:
在这里插入图片描述在这里插入图片描述
截图来自菜鸟教程:
Julia 文件(File)读写

加载和保存文件:https://cn.julialang.org/JuliaDataScience/load_save

2、Julia路径拼接函数

using CSV

# 定义文件路径
directory = "path/to/directory"
filename = "file.csv"
#表示路径的两种方式:注意双引号
#path = "C:\\Users\\Username\\Documents\\file.txt",用\\
#path = "C:/Users/Username/Documents/file.txt",用/
#不支持类似Python中r转字符

# 拼接文件路径
filepath = joinpath(directory, filename)

# 读取CSV文件
data = CSV.read(filepath,DataFrame)

# 打印数据
println(data)

3、表示一列数据最大值和最小值

struct Data
    wl::Vector{Float64}
end

data = Data([3.0, 1.0, 4.0, 1.0, 5.0])  # 示例数据

h = data.wl

max_h = maximum(h)
min_h = minimum(h)

println("h的最大值:", max_h)
println("h的最小值:", min_h)

4、Julia自定义函数并调用

# 定义一个简单的函数
function greet(name)
    println("Hello, $name! Welcome to Julia programming!")
end

# 调用函数
greet("Alice")

实际应用场景:

function estimated_discharge(rc, h)
    return discharge(rc, minimum(h))
end

# 示例数据
h = [1.0, 2.0, 3.0, 4.0, 5.0]  
rc = 0.5  

estimated_discharge_values = Float64[]  # 用于存储计算结果的数组

for height in h
    push!(estimated_discharge_values, estimated_discharge(rc, [height]))
    #push!是用于向数组(Array)添加元素的函数。当你调用push!(array, element)时,它会将element添加到array的末尾,并返回修改后的数组。
    #push!函数会改变原始数组,而不是创建一个新的数组。这种操作称为“原地修改”(in-place modification)。
end

println(estimated_discharge_values)

5、Julia循环语句

for 变量名 in 集合
    循环体
end

应用:for循环遍历一个文件夹下所有的csv文件

using CSV

# 定义文件夹路径
folder_path = "path_to_your_folder"

# 获取文件夹中所有文件的列表
files = readdir(folder_path)

# 遍历文件夹中的所有文件
for file in files
    if endswith(file, ".csv")
        # 如果文件是CSV文件,则读取文件内容
        data = CSV.read(joinpath(folder_path, file))
        # 在这里可以对数据执行任何操作
        println("处理文件: $file")
        # 例如,打印数据的前几行
        println(data[1:3, :])
    end
end

6、Julia Try-Catch语句

try
    # 尝试执行的代码块
    # 如果出现异常,代码将跳转到catch块之后的代码
    println("尝试执行代码块")
    error("这里出现了一个异常")
catch
    # 这里是在出现异常时需要执行的代码块,如果不需要处理异常,可以留空
    println("出现异常,跳过处理")
end

println("程序继续执行")

学习资料整理:
1、菜鸟教程:https://www.runoob.com/julia/julia-tutorial.html
2、Julia中文社区:https://cn.julialang.org/JuliaDataScience/

  • 9
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值