Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
  ['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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading