Home > Net >  Convert Dataframe to dictionary with one column as key and the other columns as another dict
Convert Dataframe to dictionary with one column as key and the other columns as another dict

Time:06-17

Currently I have a dataframe.

ID A B
123 a b
456 c d

I would like to convert this into a dictionary, where the key of the dictionary is the "ID" column. The value of the dictionary would be another dictionary, where the keys of that dictionary are the name of the other columns, and the value of that dictionary would be the corresponding column value. Using the example above, this would look like:

{ 123 : { A : a, B : b}, 456 : {A : c, B : d} }

I have tried: mydataframe.set_index("ID").to_dict() , but this results in a different format than the one wanted.

CodePudding user response:

Consider the following:

import pandas as pd
df = pd.DataFrame({'ID':[1,2,3], 'A':['x','y','z'], 'B':[111,222,333]})

What you're going for would be returned with the following two lines:

df.set_index('ID', inplace=True)
some_dict = {i:dict(zip(row.keys(), row.values)) for i, row in df.iterrows()}

With the output being equal to:

{1: {'A': 'x', 'B': 111}, 2: {'A': 'y', 'B': 222}, 3: {'A': 'z', 'B': 333}}

CodePudding user response:

You merely need to pass the proper orient parameter, per the documentation.

import io
pd.read_csv(io.StringIO('''ID   A   B
123 a   b
456 c   d'''), sep='\s ').set_index('ID').to_dict(orient='index')
{123: {'A': 'a', 'B': 'b'}, 456: {'A': 'c', 'B': 'd'}}

Of course, the columns maintain their string types, as indicated by the quote marks.

  • Related