[Python] Convert dictionary of lists with entries as dictionaries into dataframe with top...

Discussão em 'Python' iniciado por Stack, Fevereiro 17, 2025.

  1. Stack

    Stack Membro Participativo

    I have a dictionary of lists, each with a key string value (stock ticker) and value consisting of a list of dicts which looks like this:

    data
    Out[88]:
    {'NVDA': [{'open': 144.75, 'high': 144.21, 'low': 174.33, 'close': 210.47},
    {'open': 123.97, 'high': 128.5, 'low': 110.25, 'close': 154.09},
    {'open': 118.19, 'high': 134.81, 'low': 104.37, 'close': 149.72},
    {'open': 225.35, 'high': 126.81, 'low': 104.77, 'close': 209.46},
    {'open': 247.2, 'high': 243.25, 'low': 220.44, 'close': 186.01}],
    'MSFT': [{'open': 175.78, 'high': 213.98, 'low': 229.75, 'close': 206.59},
    {'open': 142.98, 'high': 168.42, 'low': 188.33, 'close': 232.52},
    {'open': 184.14, 'high': 163.42, 'low': 194.81, 'close': 153.03},
    {'open': 199.54, 'high': 130.26, 'low': 101.05, 'close': 102.1},
    {'open': 243.91, 'high': 119.21, 'low': 190.2, 'close': 223.31}],
    'AAPL': [{'open': 202.06, 'high': 162.54, 'low': 212.3, 'close': 226.78},
    {'open': 191.17, 'high': 153.49, 'low': 135.13, 'close': 151.83},
    {'open': 187.15, 'high': 149.75, 'low': 123.28, 'close': 247.32},
    {'open': 194.29, 'high': 175.34, 'low': 244.14, 'close': 207.45},
    {'open': 228.9, 'high': 133.26, 'low': 100.59, 'close': 129.35}]}


    ticks = ['NVDA', 'MSFT', 'AAPL']
    data = {}

    for s in ticks:
    data = []
    for _ in range(5):
    entry = {
    'open': round(random.uniform(100, 250), 2),
    'high': round(random.uniform(100, 250), 2),
    'low': round(random.uniform(100, 250), 2),
    'close': round(random.uniform(100, 250), 2)
    }
    data.append(entry)


    I'd like to convert this to a dataframe which looks like this:

    df
    Out[98]:
    tick open high low close
    0 NVDA 215.44 124.29 121.61 244.35
    1 NVDA 214.89 184.49 157.39 239.31
    2 NVDA 221.42 204.17 148.83 215.00
    3 NVDA 182.49 104.29 175.36 226.59
    4 NVDA 127.31 182.31 228.92 173.52
    5 MSFT 217.79 147.98 120.40 239.97
    6 MSFT 108.66 222.83 177.20 172.62
    7 MSFT 138.16 116.36 241.62 231.15
    8 MSFT 160.53 234.88 154.93 127.49
    9 MSFT 168.22 127.77 224.75 207.59
    10 AAPL 119.95 106.36 150.28 195.93
    11 AAPL 117.71 142.54 210.08 116.37
    12 AAPL 147.07 204.46 223.98 104.91
    13 AAPL 135.71 211.83 210.11 102.34
    14 AAPL 216.45 136.08 130.27 236.48

    Continue reading...

Compartilhe esta Página