0
votes

I have a dataframe :

name   type     price   score
Beer1   Lager    3.5     4.1
Beer2   Porte    2.9     2.8
Beer15  Lager    3.2     4.2

I would like it to convert it to this form below (because I use an algorithm that take as input this format :

[{'name': 'Beer1', 'type': 'Lager', 'price': 3.5, 'score': 4.1}, {'name': 'Beer2', 'type': 'Porte <...> t', 'price': 2.9, 'score': 2.8}, {'name': 'Beer15', 'type': 'Lager', 'price': 3.2, 'score': 4.2}]

Should I convert it to list? list of list or list of tuple? when I check with this instruction:

?beers

Type: list String form: [{'name': 'Beer1', 'type': 'Lager', 'price': 3.5, 'score': 4.1}, {'name': 'Beer2', 'type': 'Porte <...> t', 'price': 2.9, 'score': 2.8}, {'name': 'Beer15', 'type': 'Lager', 'price': 3.2, 'score': 4.2}] Length: 15 Docstring: Built-in mutable sequence.

If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.

Any idea please?

Thanks

1
[df.to_dict()] ?Shayan

1 Answers

0
votes

Use df.to_dict('records')

Link to the stack that solved the problem: Pandas DataFrame to List of Dictionaries