Search code examples
pandasexportecharts

How to export a pandas dataframe to Echarts dataset format?


Echarts dataset format looks like a CSV, but with additional square brackets. I was wondering how I could export a Pandas DataFrame directly to this format. Currently, I have to use an Emacs macro to turn exported CSV to this format.

Example of DataFrame:

|----------------+------+------+------|
| product        | 2015 | 2016 | 2017 |
|----------------+------+------+------|
| Matcha Latte   | 43.3 | 85.8 | 93.7 |
| Milk Tea       | 83.1 | 73.4 | 55.1 |
| Cheese Cocoa   | 86.4 | 65.2 | 82.5 |
| Walnut Brownie | 72.4 | 53.9 | 39.1 |
|----------------+------+------+------|

Example of expected output:

[
  ['product', 2015, 2016, 2017],
  ['Matcha Latte', 43.3, 85.8, 93.7],
  ['Milk Tea', 83.1, 73.4, 55.1],
  ['Cheese Cocoa', 86.4, 65.2, 82.5],
  ['Walnut Brownie', 72.4, 53.9, 39.1]
]

Solution

  • Code

    out = [df.columns.tolist()] + df.values.tolist()
    

    out:

    [['product', '2015', '2016', '2017'],
     ['Matcha Latte', 43.3, 85.8, 93.7],
     ['Milk Tea', 83.1, 73.4, 55.1],
     ['Cheese Cocoa', 86.4, 65.2, 82.5],
     ['Walnut Brownie', 72.4, 53.9, 39.1]]
    

    another approach

    out = df.T.reset_index().T.values.tolist()
    

    same result


    Example Code (df)

    import pandas as pd
    data1 = {'product': ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie'],
             '2015': [43.3, 83.1, 86.4, 72.4],
             '2016': [85.8, 73.4, 65.2, 53.9],
             '2017': [93.7, 55.1, 82.5, 39.1]}
    df = pd.DataFrame(data1)