Home > Enterprise >  Dataframe to nested dictionary with column names as keys
Dataframe to nested dictionary with column names as keys

Time:06-11

index    pair       number      amount
0        158_151    0000002732  104

What I want is:

{'158_151': {'number': 0000002732, 'amount': 104} ...

Is that possible?

CodePudding user response:

You are looking to the to_dict method:

df.set_index("pair").to_dict("index")
{'158_151': {'number': '000000002732', 'amount': 104}}

to_dict accept different argument for the output format. Read the doc in order to provide the correct output for your problem.

CodePudding user response:

Number column has the problem and I think it should be string.

import pandas as pd
import numpy as np

data = {'pair': ["158_151"],
        'number': ["0000002732"],
        'amount':[104]}
df = pd.DataFrame(data)
df = df.set_index('pair').to_dict("index")
print(df)

Output: {'158_151': {'number': "0000002732", 'amount': 104}}

  • Related