Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert rows in DataFrame in Python to dictionaries

For example, I have DataFrame now as

id score1   score2  score3  score4  score5 1  0.000000     0.108659    0.000000    0.078597    1 2  0.053238     0.308253    0.286353    0.446433    1 3  0.000000     0.083979    0.808983    0.233052    1 

I want to convert it as

id scoreDict 1  {'1': 0, '2': 0.1086, ...} 2  {...} 3  {...} 

Anyway to do that?

like image 747
Vicky Avatar asked Jul 09 '15 17:07

Vicky


People also ask

How do I convert a data table to a dictionary in Python?

First, search for the table header and split on spaces to define a list. Second, search for the virtual drive with "number/number" and split on spaces to define the second list. However, 'Size' will need to be special as it will need to ignore the space between number and "TB".

How do you convert a data frame to a dictionary?

to_dict() method is used to convert a dataframe into a dictionary of series or list like data type depending on orient parameter. Parameters: orient: String value, ('dict', 'list', 'series', 'split', 'records', 'index') Defines which dtype to convert Columns(series into).


1 Answers

import pandas as pd  # your df # ========================= print(df)     id  score1  score2  score3  score4  score5 0   1  0.0000  0.1087  0.0000  0.0786       1 1   2  0.0532  0.3083  0.2864  0.4464       1 2   3  0.0000  0.0840  0.8090  0.2331       1  # to_dict # ========================= df.to_dict(orient='records')  Out[318]:  [{'id': 1.0,   'score1': 0.0,   'score2': 0.10865899999999999,   'score3': 0.0,   'score4': 0.078597,   'score5': 1.0},  {'id': 2.0,   'score1': 0.053238000000000001,   'score2': 0.308253,   'score3': 0.28635300000000002,   'score4': 0.44643299999999997,   'score5': 1.0},  {'id': 3.0,   'score1': 0.0,   'score2': 0.083978999999999998,   'score3': 0.80898300000000001,   'score4': 0.23305200000000001,   'score5': 1.0}] 
like image 122
Jianxun Li Avatar answered Sep 27 '22 23:09

Jianxun Li