LoginSignup
1
3

More than 3 years have passed since last update.

juliaでcsvに読み書きする

Last updated at Posted at 2021-02-01

julia(v1.5.2)でcsvに読み書きをします. いくつかのサイトに書かれているCSV.read()を上手く使えず, 手こずったためまとめました.

読み込み

読み込まれるcsvファイルをhoge.csvとします.

hoge.csv
a, b, c
1, 0.1, 34
2, 1, 54
3, 10, 0.4
4, 99, 554
read.jl
using CSV
using DataFrames

dfr = CSV.File("./hoge.csv",  header=true, delim=',') |> DataFrame
print(dfr)

出力は次のようになります.

4×3 DataFrame
 Row │ a      b        c       
     │ Int64  Float64  Float64 
─────┼─────────────────────────
   1 │     1      0.1     34.0
   2 │     2      1.0     54.0
   3 │     3     10.0      0.4
   4 │     4     99.0    554.0

書き込み

write.jl
using CSV
using DataFrames

data = [1  0.1 ;
        2  1.0 ;
        3  9.9 ];
dfw = DataFrame(data)
CSV.write("./fuga.csv", dfw, header=true, delim=", ")

出力ファイルは次のようになります.

fuga.csv
x1, x2
1.0, 0.1
2.0, 1.0
3.0, 9.9

delim=','とするよりdelim=", "とするほうが出力ファイルの見た目が少し良くなります.
CSV.File(), CSV.write()のいずれでもheader,delimは省略可能です

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3