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

Pandas: dataframe to array of rows with index as additional column

With panda, when I print a dataframe, my result is

   Description Test
0        Some    3
1       Thing    e
2        Test  NaN

For my front end I need to things, one is an object array of headers, and one an object array of rows. The first is not a problem, I made that with columns and a function. The rows however are trickier. I need this result:

[
{'id': 0, 'description':'some', 'test':'3'},
{'id': 1, 'description':'Thing', 'test':'e'},
{'id': 2, 'description':'Test', 'test':'NaN'},
]

The NaN is an empty, I forgot to pass a value for it. I could make a funtion and use pydash with some loops maybe, but is there a faster way to do this?

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

>Solution :

Reset current numeric index to a named column id and convert dataframe into list of records, with a single line:

df.reset_index(names='id').to_dict('records')

[{'id': 0, 'Description': 'Some', 'Test': '3'},
 {'id': 1, 'Description': 'Thing', 'Test': 'e'},
 {'id': 2, 'Description': 'Test', 'Test': nan}]
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