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

Convert this list of dictionaries into a list of panda dataframes based on key-value pair in list of dictionaries

I have this list of dictionaries in python.

l=[
    {
        "TIME": "20220414 12:00:00",
        "Ticker": "AAA",
        "value": "12.0"
    },
    {
        "TIME": "20220414 11:00:00",
        "Ticker": "AAA",
        "value": "13.0"
    },
    {
        "TIME": "20220414 12:00:00",
        "Ticker": "BBB",
        "value": "15.0"
    },
    {
        "TIME": "20220414 11:00:00",
        "Ticker": "BBB",
        "value": "16.0"
    },
    {
        "TIME": "20220414 12:00:00",
        "Ticker": "CCC",
        "value": "17.0"
    },
    {
        "TIME": "20220414 11:00:00",
        "Ticker": "CCC",
        "value": "18.0"
    }   
]

I want to convert it into a list of panda dataframes based on Ticker.

The converted output will look something like this;

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

enter image description here

The list of 3 dictionaries will be converted into a list of 3 panda dataframes.

I am using python 3.9

>Solution :

You can use the DataFrame constructor combined with groupby and a list comprehension:

out = [d.set_index('Ticker') for _,d in pd.DataFrame(l).groupby('Ticker')]

output:

[                     TIME value
 Ticker                         
 AAA     20220414 12:00:00  12.0
 AAA     20220414 11:00:00  13.0,
                      TIME value
 Ticker                         
 BBB     20220414 12:00:00  15.0
 BBB     20220414 11:00:00  16.0,
                      TIME value
 Ticker                         
 CCC     20220414 12:00:00  17.0
 CCC     20220414 11:00:00  18.0]

NB. I assumed "Name" in the first dictionary should be "Ticker" (and fixed the typo in your question). If this was the real data and not a typo, you first need to change "Name" into "Ticker":

out = [d.set_index('Ticker') for _,d in
       pd.DataFrame(l).assign(Ticker=lambda d: d['Ticker'].fillna(d.pop('Name')))]
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