How to convert a csv file into arrays (one 1D and one 2D)?

edited February 2015 in How To...

Hi, I would like to convert a csv table looking like this (without blank lines inside)

header1, header2, header3

text1,2,3

text2,0,1

text3,0,0

into 2 arrays looking like this {{2,3},{0,1},{0,0}} and this {text1, text2, text3} Could anyone help me? Thanks a lot kamca

Answers

  • edited August 2014 Answer ✓

    remarks

    instead of the 2D array you could use an 1D array of PVector?

    anyway this {{2,3},{0,1},{0,0}} I call points

    this {text1, text2, text3} I call texts

    how to

    you could look at loadStrings() for loading the file into originalText (see reference).

    the for-loop i over the resulting String array originalText

    (pseudo-code)

    use split: splitResult = split ....

    String[] splitResult = split (originalText[i], ",");
    

    and then:

    {
    points [i] [0] = splitResult [1];
    points [i] [1] = splitResult [2];
    texts [i]      = splitResult [0];
    
    }
    

    Best, Chrisir ;-)

  • edited February 2015 Answer ✓

    How about this 1?: ;;)

    // forum.processing.org/two/discussion/6668/
    // how-to-convert-a-csv-file-into-arrays-one-1d-and-one-2d
    
    import java.util.List;
    
    static final
    void splitTableTypes(Table t, String[] s, PVector[] p) {
      int idx = 0;
      for (TableRow tr: t.rows()) {
        s[idx] = tr.getString(0);
        p[idx++] = new PVector(tr.getFloat(1), tr.getFloat(2));
      }
    }
    
    static final String CSV = "coords.csv";
    
    String[] texts;
    PVector[] coords;
    
    void setup() {
      size(800, 600, JAVA2D);
      smooth(4);
    
      Table table = loadTable(CSV, "header");
      int rows = table.getRowCount();
    
      texts  = new String[rows];
      coords = new PVector[rows];
    
      table.setColumnTypes(new int[] {
        Table.STRING, Table.FLOAT, Table.FLOAT
      }
      );
    
      splitTableTypes(table, texts, coords);
    
      for (int i = 0; i != rows;
        println("#" + i + " \t" + texts[i] + " \t" + coords[i++]));
    
      exit();
    }
    
  • Thank you very much for both answers, you got me an idea how to sort the problem in my script in even easily ;)

Sign In or Register to comment.