Python Pandas equivalent in JavaScript

前端 未结 9 1128
时光取名叫无心
时光取名叫无心 2021-01-29 17:24

With this CSV example:

   Source,col1,col2,col3
   foo,1,2,3
   bar,3,4,5

The standard method I use Pandas is this:

  1. Parse CSV<

9条回答
  •  终归单人心
    2021-01-29 18:19

    It's pretty easy to parse CSV in javascript because each line's already essentially a javascript array. If you load your csv into an array of strings (one per line) it's pretty easy to load an array of arrays with the values:

    var pivot = function(data){
        var result = [];
        for (var i = 0; i < data.length; i++){
            for (var j=0; j < data[i].length; j++){
                if (i === 0){
                    result[j] = [];
                }
                result[j][i] = data[i][j];
            }
        }
        return result;
    };
    
    var getData = function() {
        var csvString = $(".myText").val();
        var csvLines = csvString.split(/\n?$/m);
    
        var dataTable = [];
    
        for (var i = 0; i < csvLines.length; i++){
            var values;
            eval("values = [" + csvLines[i] + "]");
            dataTable[i] = values;
        }
    
        return pivot(dataTable);
    };
    

    Then getData() returns a multidimensional array of values by column.

    I've demonstrated this in a jsFiddle for you.

    Of course, you can't do it quite this easily if you don't trust the input - if there could be script in your data which eval might pick up, etc.

提交回复
热议问题