Reading and Writing Files
Text Files
# Writing to a file
open("example.txt", "w") do f
write(f, "Hello, Julia!")
end
# Reading from a file
content = read("example.txt", String)
println(content)
CSV Files
using CSV, DataFrames
# Read CSV
df = CSV.read("data.csv", DataFrame)
# Write CSV
CSV.write("output.csv", df)
DataFrames
DataFrames are tabular data structures similar to pandas in Python or data.frames in R.
Creating DataFrames
using DataFrames
# Create from columns
df = DataFrame(
name = ["Alice", "Bob", "Charlie"],
age = [25, 30, 35],
city = ["Helsinki", "Espoo", "Tampere"]
)
| Row |
name |
age |
city |
|
String |
Int64 |
String |
| 1 |
Alice |
25 |
Helsinki |
| 2 |
Bob |
30 |
Espoo |
| 3 |
Charlie |
35 |
Tampere |
Basic Operations
# Select columns
df[:, :name]
3-element Vector{String}:
"Alice"
"Bob"
"Charlie"
# Filter rows
filter(row -> row.age > 25, df)
| Row |
name |
age |
city |
|
String |
Int64 |
String |
| 1 |
Bob |
30 |
Espoo |
| 2 |
Charlie |
35 |
Tampere |
# Add new column
df.country = ["Finland", "Finland", "Finland"]
df
| Row |
name |
age |
city |
country |
|
String |
Int64 |
String |
String |
| 1 |
Alice |
25 |
Helsinki |
Finland |
| 2 |
Bob |
30 |
Espoo |
Finland |
| 3 |
Charlie |
35 |
Tampere |
Finland |
Grouping and Aggregation
using Statistics
# Group by and summarize
gdf = groupby(df, :country)
combine(gdf, :age => mean => :avg_age)
| Row |
country |
avg_age |
|
String |
Float64 |
| 1 |
Finland |
30.0 |
Working with Geoscientific Data
Loading Geophysical Data
using DelimitedFiles
# Read space-delimited data
data = readdlm("gravity_data.txt")
# Extract columns
x, y, gz = data[:, 1], data[:, 2], data[:, 3]
NetCDF Files
using NCDatasets
# Read NetCDF
ds = Dataset("climate_data.nc")
temp = ds["temperature"][:]
close(ds)