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?

  • Do you want to keep the Bfield and MOKEvoltage for each file? – That Gravity Guy Oct 12 at 0:36
  • No I don't need it for every file. – Jashan Singhal Oct 12 at 2:11
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
  • files = "sample_data_" <> ToString[#] <> ".csv" & /@ Range[10] to create the filenames through sample_data_10.csv – GenericAccountName Oct 12 at 3:46

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

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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