简体   繁体   English

python - 使用 pandas 的列表字典

[英]python - Dict of Dict of List using pandas

I want to group a pandas DataFrame as below.我想将 pandas DataFrame 分组如下。 A Dictionary with stocks, and each stock has its own dictionary to capture date & timestamp.带有股票的字典,每只股票都有自己的字典来捕获日期和时间戳。 And each of those entries will have the OHLC values for that period.这些条目中的每一个都将具有该时期的 OHLC 值。 Since this is run in Live market, the date and timestamp needs to be a dictionary to reupdate the values.由于这是在实时市场中运行的,因此日期和时间戳需要是一个字典才能重新更新值。 As the initial DataFrame has around 100,000 entries, creating the Dict of Dict of List manually takes over 30 seconds.由于最初的 DataFrame 有大约 100,000 个条目,因此手动创建 Dict of List 的 Dict 需要 30 多秒。

Stock(Dict)     Day(Dict)               Open, High, Low, Close(List)    
A1              2023-01-01 09:15:00     100, 102, 99, 101
                2023-01-02 09:15:20     100, 102, 99, 101
B1              2023-01-01 09:15:00     100, 102, 99, 101
                2023-01-02 09:20:00     100, 102, 99, 101

I am able to create the Dict of Dicts but only populate one value from Open, High, Low, Close我能够创建 Dict of Dicts,但只能从 Open、High、Low、Close 中填充一个值

g = df_symbols_all.set_index('day').groupby('symbol').apply(lambda x: x.high.to_dict()).to_dict()

在此处输入图像描述

If I try to pass all values, it does not create the date & timestamp dictionary.如果我尝试传递所有值,它不会创建日期和时间戳字典。

k= df_symbols_all.set_index('day').groupby('symbol').apply(lambda x: (x.open.to_dict(), x.high.to_dict(), x.low.to_dict(), x.close.to_dict())).to_dict()

在此处输入图像描述

Any help will be appreciated, thanks.任何帮助将不胜感激,谢谢。

You could create a new column that combines the ('open', 'close','high','low') into a single column (this can be performed fast):您可以创建一个新列,将 ('open', 'close','high','low') 组合成一个列(这可以快速执行):

df_symbols_all['open_high_low_close'] = df_symbols_all[['open','close','high','low']].values.tolist()

and then perform the grouping as you suggested然后按照您的建议执行分组

g = df_symbols_all.set_index('day').groupby('symbol').apply(lambda x: x.open_high_low_close.to_dict()).to_dict()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM