Import / export a sample via a CSV file

In this example we are going to import and export a data sample from/to a CSV file.

import openturns as ot

ot.Log.Show(ot.Log.NONE)

Create a sample from a 2-d Gaussian distribution.

sample = ot.Normal(2).getSample(5)
sample.setDescription(["u1", "u2"])

Write a CSV file. Warning: the default separator is ‘;’.

sample.exportToCSVFile("sample.csv", ",")

Print the content of the written file.

with open("sample.csv", "r") as f:
    for line in f.readlines():
        print(line, end="")
"u1","u2"
6.0820165121876457e-01,-1.2661731022166567e+00
-4.3826561996041397e-01,1.2054782008285756e+00
-2.1813852346165143e+00,3.5004208653029067e-01
-3.5500704918563969e-01,1.4372493101409030e+00
8.1066798246948368e-01,7.9315601145976999e-01

Read the previous CSV file.

sample = ot.Sample.ImportFromCSVFile("sample.csv", ",")
print(sample)
    [ u1        u2        ]
0 : [  0.608202 -1.26617  ]
1 : [ -0.438266  1.20548  ]
2 : [ -2.18139   0.350042 ]
3 : [ -0.355007  1.43725  ]
4 : [  0.810668  0.793156 ]