0
$\begingroup$

I have a number of datasets (csv) which require the same manipulation and plotting, but I don't want to repeatedly write the same set of code again and again. What is the best way to do this?

Piece of code looks like this -

data1 = Import["sample_data_1.csv", "CSV"];
data1 = data1[[11 ;; -1, All]];
Bfield = data1[[All, 1]];
MOKEvoltage = data1[[All, 2]];
data1list = Transpose@{Bfield, MOKEvoltage};
p1 = ListPlot[data1list]

Now I wat to repeat the same procedure for "sample_data_2.csv","sample_data_3.csv", and so on.

What is the most efficient way to do so?

$\endgroup$
  • $\begingroup$ Do you want to keep the Bfield and MOKEvoltage for each file? $\endgroup$ – That Gravity Guy Oct 12 '18 at 0:36
  • $\begingroup$ No I don't need it for every file. $\endgroup$ – Indeterminate Oct 12 '18 at 2:11
1
$\begingroup$
files = {"sample_data_1.csv", "sample_data_2.csv", "sample_data_3.csv"}

plot[file_] := Module[{data1, Bfield, MOKEvoltage, data1list},
  data1 = Import[file, "CSV"];
  data1 = data1[[11 ;; -1, All]];
  Bfield = data1[[All, 1]];
  MOKEvoltage = data1[[All, 2]];
  data1list = Transpose@{Bfield, MOKEvoltage};
  ListPlot[data1list]]

plot /@ files
$\endgroup$
  • $\begingroup$ files = "sample_data_" <> ToString[#] <> ".csv" & /@ Range[10] to create the filenames through sample_data_10.csv $\endgroup$ – GenericAccountName Oct 12 '18 at 3:46
0
$\begingroup$

Since you only want to plot each data set, most of the manipulation cancels itself out.

With[{data = {{a, b}, {c, d}}}, Transpose@{data[[;; , 1]], data[[;; , 2]]}]

{{a, b}, {c, d}}

In the end what you want is

ListPlot[Import[#][[11 ;;]]] & /@ {"sample_data_1.csv", "sample_data_2.csv", ...}

For example

ListPlot[#[[11 ;;]]] & /@ RandomReal[{0., 1.}, {2, 20, 2}] // GraphicsRow

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.