Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do i convert python dictionary to pandas framework

I Have a JSON type dictionary in Python like this:

d = {'2022-12-21 20:00:00': {'1. open': '135.5900',
                             '2. high': '135.7300',
                             '3. low': '135.5900',
                             '4. close': '135.6700',
                             '5. volume': '18031'},
     '2022-12-21 19:45:00': {'1. open': '135.5700',
                             '2. high': '135.6000',
                             '3. low': '135.5500',
                             '4. close': '135.5700',
                             '5. volume': '4253'}}

and I would like to convert in into a pandas dataframe like:

  |timestamp           |open |high |low  |close|volume 
1 |2022-12-21 20:00:00 | 135 |135  | 135 | 135 |18031
2 |2022-12-21 19:45:00 | 134 | 112 | 123 | 231 |24124

I tried to do it with:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df = pd.DataFrame.from_dict(d, orient='index')

but after this the dates become the indexing column and I want an indexing column as well:

enter image description here

>Solution :

The dates become the index by default. You can reset the index and rename the dates column using the reset_index method:

import pandas as pd

d = {'2022-12-21 20:00:00': {'1. open': '135.5900',
                             '2. high': '135.7300',
                             '3. low': '135.5900',
                             '4. close': '135.6700',
                             '5. volume': '18031'},
     '2022-12-21 19:45:00': {'1. open': '135.5700',
                             '2. high': '135.6000',
                             '3. low': '135.5500',
                             '4. close': '135.5700',
                             '5. volume': '4253'}}

df = pd.DataFrame.from_dict(d, orient='index')
df.reset_index(inplace=True, names="date")
print(df)

Gives:

                  date   1. open   2. high    3. low  4. close 5. volume
0  2022-12-21 20:00:00  135.5900  135.7300  135.5900  135.6700     18031
1  2022-12-21 19:45:00  135.5700  135.6000  135.5500  135.5700      4253

The inplace argument makes sure you modify the dataframe instead of creating a new one (the default), and the names argument renames the column that used to be index.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading