-1

I'm trying to convert dataframe rows to a dict.

df

       a            b
  
 0    paul         active
 1    marcus     inactive
 2    bruno        active
 3    scott      inactive
 4    anthony      active

To a dict from rows:

final_dict = {'paul':'active','marcus':'inactive','bruno':'active','scott':'inactive','anthony':'active'}
  • Does this answer your question? [Convert a Pandas DataFrame to a dictionary](https://stackoverflow.com/questions/26716616/convert-a-pandas-dataframe-to-a-dictionary) – azro Jul 02 '20 at 19:05
  • value in the above reference is either in list or dict. –  Jul 02 '20 at 19:10
  • Duplicate of https://stackoverflow.com/questions/18695605/python-pandas-dataframe-to-dictionary, which was a duplicate of https://stackoverflow.com/questions/18012505/python-pandas-dataframe-columns-convert-to-dict-key-and-value – Ian Logie Jul 02 '20 at 19:47

2 Answers2

1

You can use this

import pandas as pd
df.to_dict(orient='records')

you can refer here

Manoj Kumar
  • 745
  • 2
  • 8
  • 29
  • This is a beautiful duplicate that already has a nice answer, please delete your post and flag the question. If you keep your answer, you'll make next guys that come here stop their research and don't know the full detail, thanks – azro Jul 02 '20 at 19:06
0

Here is how:

d = {k:df['b'][df[df['a']==k].index.values[0]] for k in df['a']}


Breaking it down, here is how to find the index of a specific value in column:

val = 'value' # The value we want to find the index of
col = 'a' # The column the value is in
index = df[df[col]==val].index.values[0] # Here is how to find the index

Here is how you can find the value of a specific column given an index:

index = 3 The index of the column we want to find the value of
col = 'a' # The column which want to find a value in
value = df[col][index] # Here is how to find the value

So the dictionary will basically have the values of column a, and the values of column b, which we find those values that correspond to the values from a by using the indexes.

Red
  • 26,798
  • 7
  • 36
  • 58