Skip to content

to_dict() equivalent #404

Open
Open
@kylemcdonald

Description

@kylemcdonald

I would like to convert a DataFrame to a JSON object the same way that Pandas does with to_dict().

toJSON() treats rows as elements in an array, and ignores the index labels. But to_dict() uses the index as keys.

Here is an example of what I have in mind:

function to_dict(df) {
    const rows = df.toJSON();
    const entries = df.index.map((e, i) => ({ [e]: rows[i] }));
    return Object.assign({}, ...entries);
}

Perhaps this could work as DataFrame.toDict() or as an option in the behavior of toJSON().

Example DataFrame:

DataFrame {
  '$dataIncolumnFormat': [ ...  ],
  '$index': [
    'OpenSea',
    'Nifty Gateway',
    'Rarible',
    'Foundation',
    'MakersPlace',
    'SuperRare'
  ],
  '$columns': [ 'total_tco2', 'daily_tco2' ],
  '$dtypes': [ 'float32', 'float32' ],
  '$isSeries': false,
  '$config': Configs {
    tableDisplayConfig: {},
    tableMaxRow: 10,
    tableMaxColInConsole: 10,
    dtypeTestLim: 20,
    lowMemoryMode: false
  },
  '$data': [
    [ 503722.6664227946, 482.4379185267857 ],
    [ 45685.642055631906, 29.24222128731864 ],
    [ 27768.712144985853, 13.813942364283971 ],
    [ 14083.993252908811, 37.805406842912944 ],
    [ 2706.74906889617, 0.27648426592350006 ],
    [ 2845.9445369987516, 1.8170695304870605 ]
  ]
}

Example output of df.toJSON():

[
  { total_tco2: 503722.6664227946, daily_tco2: 482.4379185267857 },
  { total_tco2: 45685.642055631906, daily_tco2: 29.24222128731864 },
  { total_tco2: 27768.712144985853, daily_tco2: 13.813942364283971 },
  { total_tco2: 14083.993252908811, daily_tco2: 37.805406842912944 },
  { total_tco2: 2706.74906889617, daily_tco2: 0.27648426592350006 },
  { total_tco2: 2845.9445369987516, daily_tco2: 1.8170695304870605 }
]

Example output of to_dict(df):

{
  OpenSea: { total_tco2: 503722.6664227946, daily_tco2: 482.4379185267857 },
  'Nifty Gateway': { total_tco2: 45685.642055631906, daily_tco2: 29.24222128731864 },
  Rarible: { total_tco2: 27768.712144985853, daily_tco2: 13.813942364283971 },
  Foundation: { total_tco2: 14083.993252908811, daily_tco2: 37.805406842912944 },
  MakersPlace: { total_tco2: 2706.74906889617, daily_tco2: 0.27648426592350006 },
  SuperRare: { total_tco2: 2845.9445369987516, daily_tco2: 1.8170695304870605 }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions