Python Pandas equivalent in JavaScript

Ceaveat The following is applicable only to d3 v3, and not the latest d4v4!

I am partial to d3.js, and while it won't be a total replacement for Pandas, if you spend some time learning its paradigm, it should be able to take care of all your data wrangling for you. (And if you wind up wanting to display results in the browser, it's ideally suited to that.)

Example. My CSV file data.csv:

name,age,color
Mickey,65,black
Donald,58,white
Pluto,64,orange

In the same directory, create an index.html containing the following:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8"/>
    <title>My D3 demo</title>

    <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
  </head>
  <body>

      <script charset="utf-8" src="demo.js"></script>
  </body>
</html>

and also a demo.js file containing the following:

d3.csv('/data.csv',

       // How to format each row. Since the CSV file has a header, `row` will be
       // an object with keys derived from the header.
       function(row) {
         return {name : row.name, age : +row.age, color : row.color};
       },

       // Callback to run once all data's loaded and ready.
       function(data) {
         // Log the data to the JavaScript console
         console.log(data);

         // Compute some interesting results
         var averageAge = data.reduce(function(prev, curr) {
           return prev + curr.age;
         }, 0) / data.length;

         // Also, display it
         var ulSelection = d3.select('body').append('ul');
         var valuesSelection =
             ulSelection.selectAll('li').data(data).enter().append('li').text(
                 function(d) { return d.age; });
         var totalSelection =
             ulSelection.append('li').text('Average: ' + averageAge);
       });

In the directory, run python -m SimpleHTTPServer 8181, and open http://localhost:8181 in your browser to see a simple listing of the ages and their average.

This simple example shows a few relevant features of d3:

  • Excellent support for ingesting online data (CSV, TSV, JSON, etc.)
  • Data wrangling smarts baked in
  • Data-driven DOM manipulation (maybe the hardest thing to wrap one's head around): your data gets transformed into DOM elements.

This wiki will summarize and compare many pandas-like Javascript libraries.

In general, you should check out the d3 Javascript library. d3 is very useful "swiss army knife" for handling data in Javascript, just like pandas is helpful for Python. You may see d3 used frequently like pandas, even if d3 is not exactly a DataFrame/Pandas replacement (i.e. d3 doesn't have the same API; d3 does not have Series / DataFrame classes with methods that match the pandas behavior)

Ahmed's answer explains how d3 can be used to achieve some DataFrame functionality, and some of the libraries below were inspired by things like LearnJsData which uses d3 and lodash.

As for DataFrame-style data transformation (splitting, joining, group by etc) , here is a quick list of some of the Javascript libraries.

Note some libraries are Node.js aka Server-side Javascript, some are browser-compatible aka client-side Javascript, and some are Typescript. So use the option that's right for you.

  • danfo-js (browser-support AND NodeJS-support)
    • From Vignesh's answer

    • danfo (which is often imported and aliased as dfd); has a basic DataFrame-type data structure, with the ability to plot directly

    • Built by the team at Tensorflow: "One of the main goals of Danfo.js is to bring data processing, machine learning and AI tools to JavaScript developers. ... Open-source libraries like Numpy and Pandas..."

    • pandas is built on top of numpy; likewise danfo-js is built on tensorflow-js

    • please note danfo may not (yet?) support multi-column indexes

  • pandas-js
    • UPDATE The pandas-js repo has not been updated in awhile
    • From STEEL and Feras' answers
    • "pandas.js is an open source (experimental) library mimicking the Python pandas library. It relies on Immutable.js as the NumPy logical equivalent. The main data objects in pandas.js are, like in Python pandas, the Series and the DataFrame."
  • dataframe-js
    • "DataFrame-js provides an immutable data structure for javascript and datascience, the DataFrame, which allows to work on rows and columns with a sql and functional programming inspired api."
  • data-forge
    • Seen in Ashley Davis' answer
    • "JavaScript data transformation and analysis toolkit inspired by Pandas and LINQ."
    • Note the old data-forge JS repository is no longer maintained; now a new repository uses Typescript
  • jsdataframe
    • "Jsdataframe is a JavaScript data wrangling library inspired by data frame functionality in R and Python Pandas."
  • dataframe
    • "explore data by grouping and reducing."
  • SQL Frames
    • "DataFrames meet SQL, in the Browser"
    • "SQL Frames is a low code data management framework that can be directly embedded in the browser to provide rich data visualization and UX. Complex DataFrames can be composed using familiar SQL constructs. With its powerful built-in analytics engine, data sources can come in any shape, form and frequency and they can be analyzed directly within the browser. It allows scaling to big data backends by transpiling the composed DataFrame logic to SQL."

Then after coming to this question, checking other answers here and doing more searching, I found options like:

  • Apache Arrow in JS
    • Thanks to user Back2Basics suggestion:
    • "Apache Arrow is a columnar memory layout specification for encoding vectors and table-like containers of flat and nested data. Apache Arrow is the emerging standard for large in-memory columnar data (Spark, Pandas, Drill, Graphistry, ...)"
  • polars
    • Polars is a blazingly fast DataFrames library implemented in Rust using Apache Arrow Columnar Format as memory model.
  • Observable
    • At first glance, seems like a JS alternative to the IPython/Jupyter "notebooks"
    • Observable's page promises: "Reactive programming", a "Community", on a "Web Platform"
    • See 5 minute intro here
  • portal.js (formerly recline; from Rufus' answer)
    • MAY BE OUTDATED: Does not use a "DataFrame" API
    • MAY BE OUTDATED: Instead emphasizes its "Multiview" (the UI) API, (similar to jQuery/DOM model) which doesn't require jQuery but does require a browser! More examples
    • MAY BE OUTDATED: Also emphasizes its MVC-ish architecture; including back-end stuff (i.e. database connections)
  • js-data
    • Really more of an ORM! Most of its modules correspond to different data storage questions (js-data-mongodb, js-data-redis, js-data-cloud-datastore), sorting, filtering, etc.
    • On plus-side does work on Node.js as a first-priority; "Works in Node.js and in the Browser."
  • miso (another suggestion from Rufus)
    • Impressive backers like Guardian and bocoup.
  • AlaSQL
    • "AlaSQL" is an open source SQL database for Javascript with a strong focus on query speed and data source flexibility for both relational data and schemaless data. It works in your browser, Node.js, and Cordova."
  • Some thought experiments:
    • "Scaling a DataFrame in Javascript" - Gary Sieling

Here are the criteria we used to consider the above choices

  • General Criteria
    • Language (NodeJS vs browser JS vs Typescript)
    • Dependencies (i.e. if it uses an underlying library / AJAX/remote API's)
    • Actively supported (active user-base, active source repository, etc)
    • Size/speed of JS library
  • Panda's criterias in its R comparison
    • Performance
    • Functionality/flexibility
    • Ease-of-use
  • Similarity to Pandas / Dataframe API's
    • Specifically hits on their main features
    • Data-science emphasis
    • Built-in visualization functions
    • Demonstrated integration in combination with other tools like Jupyter (interactive notebooks), etc

I've been working on a data wrangling library for JavaScript called data-forge. It's inspired by LINQ and Pandas.

It can be installed like this:

npm install --save data-forge

Your example would work like this:

var csvData = "Source,col1,col2,col3\n" +
    "foo,1,2,3\n" +
    "bar,3,4,5\n";

var dataForge = require('data-forge');
var dataFrame = 
    dataForge.fromCSV(csvData)
        .parseInts([ "col1", "col2", "col3" ])
        ;

If your data was in a CSV file you could load it like this:

var dataFrame = dataForge.readFileSync(fileName)
    .parseCSV()
    .parseInts([ "col1", "col2", "col3" ])
    ;

You can use the select method to transform rows.

You can extract a column using getSeries then use the select method to transform values in that column.

You get your data back out of the data-frame like this:

var data = dataFrame.toArray();

To average a column:

 var avg = dataFrame.getSeries("col1").average();

There is much more you can do with this.

You can find more documentation on npm.