close

How to convert rows in DataFrame in Python to dictionaries

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to convert rows in DataFrame in Python to dictionaries in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to convert rows in DataFrame in Python to dictionaries?

  1. How to convert rows in DataFrame in Python to dictionaries?

    For others like me coming to this question but looking to do the following: Create a dict row by row to map a column based of the value of the adjacent column.

  2. convert rows in DataFrame in Python to dictionaries

    For others like me coming to this question but looking to do the following: Create a dict row by row to map a column based of the value of the adjacent column.

Method 1

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}]

Method 2

For others like me coming to this question but looking to do the following: Create a dict row by row to map a column based of the value of the adjacent column.

Here’s our mapping table:

  Rating    y
0  AAA      19
1  AA1      18
2  AA2      17
3  AA3      16
4  A1       15
5  A2       14
6  A3       13
      ...
19 D       0

IN:

import pandas as pd
df_map.set_index('y')
dict_y = df_map['Rating'].to_dict()

OUT:

{19: 'AAA',
 18: 'AA1',
 17: 'AA2',
 16: 'AA3',
 15: 'A1',
 14: 'A2',
 13: 'A3',
 12: 'BBB1',
 11: 'BBB2',
 10: 'BBB3',
 9: 'BB1',
 8: 'BB2',
 7: 'BB3',
 6: 'B1',
 5: 'B2',
 4: 'B3',
 3: 'CCC1',
 2: 'CCC2',
 1: 'D'}

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read